var today = getDate($('#doc').data('today'));
$(function() {
    // 订单状态数组  
    window.orderStatus = {
        'booked': lang('status.reserve'),
        'paied': lang('status.payment'),
        'checkin': lang('status.checkIn'),
        'checkout': lang('status.checkOut'),
        'cancelled': lang('status.canceled'),
        'expired': lang('status.expired'),
        'needOut': lang('status.needOut'),
    };
    $('#orderCancelContent, #orderCheckInContent, #orderEditContent, #orderCheckOutContent').on('click', '.dropdown-menu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var toggle = liItem.parents('.dropdown-menu').siblings('[data-toggle="dropdown"]');
        liItem.addClass('active');
        liItem.siblings().removeClass('active');
        var value = liItem.data('value');
        var name = item.text();
        toggle.data('value', value);
        toggle.find('.info').html(name);
        if(window.edithour){
            calculateEditHourContentTotal()         ;   
        }else if(window.editlong){
            calculateEditLongContentTotal();
        }else{
            calculateEditContentTotal();           
        }        
    }); 
    // 订单详情初始化
    var getOrderInfo = function(param){
    	ajaxRequest('/Home/Order/getOrder', param, 'post', function(data){
    		window.orderInfoForShow = data;
            window.getOrderInfoStatus++;
    		showOrderInfo();
    	}, function(error) {
            hideMainLoading();
        });
    };
    var getPriceData = function(startDate){
	    var timestamp = startDate.getTime() + 3*86400000;
	    var submitDate = new Date(timestamp);
	    var submitDateMonth = submitDate.getMonth()+1;
	    var submitDateDay = submitDate.getDate();
	    var submitDateFormat = submitDate.getFullYear()+(submitDateMonth<10?'-0':'-')+submitDateMonth+(submitDateDay<10?'-0':'-')+submitDateDay;
	    var param = {};
	    param.hotel = window.currentHotel;
	    param.date = submitDateFormat;
	    if(!window.roomPriceDate){
		    ajaxRequest('/Home/Room/getPriceByHotelId', param, 'post', function(result){
		    	var priceData = new Array();	        
		    	for(var i = 0; i < result.data.length; i++){
		    		var room = result.data[i];
		    		for(var j = 0; j < room.prices.length; j++){
		    			var price = room.prices[j];
		    			priceData[room.room_id + '_' + price.timestamp] = price.price;
		    		}
		    	}
		        window.roomPriceDate = submitDateFormat;
		    	window.roomPrices = priceData;
		    	window.getOrderInfoStatus++;
		    	showOrderInfo();
		    });
	    }else{
	    	window.getOrderInfoStatus++;
	    	showOrderInfo();
	    };
    };
    var showOrderInfo = function(){
    	if(window.getOrderInfoStatus==2){
    		initOrderInfoSuccess(window.orderInfoForShow);
    	};
    };
    $('#orderListBody').on('click', '.order-item:not(.checkout),.order-item-container>.order-item-tip', function(e) {
        e.stopPropagation();
        var orderItem = $(this);
        var orderRoomValue = orderItem.data('value');
        var roomId = orderItem.parents('td').data('value');
        var orderValue = orderItem.data('parent');
        
        // showMainLoading();
        // 请求订单数据
        var param = {};
        param.hotel = window.currentHotel;
        param.order = orderValue;
        var initContent = $('#orderInitContent');
        initContent.data('value', orderRoomValue);
        initContent.data('parent', orderValue);
        initContent.data('roomid', roomId);
        $('#orderDetailModal .modal-content').css('left', '0px').css('top', '0px');
    	window.getOrderInfoStatus = 0;
    	getOrderInfo(param);
    	getPriceData(getDate(window.startDate)); 
    });
    //钟点房
    $('#orderListBody').on('click', '.order-hour', function(e) {
        e.stopPropagation();
        var orderItem = $(this);
        var orderRoomValue = orderItem.data('value');
        var roomId = orderItem.parents('td').data('value');
        var orderValue = orderItem.data('parent');
        if(orderRoomValue != undefined){
            // showMainLoading();
            // 请求订单数据
            var param = {};
            param.hotel = window.currentHotel;
            param.order = orderValue;
            var initContent = $('#orderInitContent');
            initContent.data('value', orderRoomValue);
            initContent.data('parent', orderValue);
            initContent.data('roomid', roomId);
            $('#orderDetailModal .modal-content').css('left', '0px').css('top', '0px');
            window.getOrderInfoStatus = 0;
            getOrderInfo(param);
            getPriceData(getDate(window.startDate));             
        }

    });     
    $('#orderListBody').on('click', '.order-hour-container>.order-item-tip', function(e) {
        e.stopPropagation();        
        var orderItem = $(this);
        var orderRoomValue = orderItem.data('value');
        var roomId = orderItem.parents('td').data('value');
        var orderValue = orderItem.data('parent');
        // showMainLoading();
        // 请求订单数据
        var param = {};
        param.hotel = window.currentHotel;
        param.order = orderValue;
        var initContent = $('#orderInitContent');
        initContent.data('value', orderRoomValue);
        initContent.data('parent', orderValue);
        initContent.data('roomid', roomId);
        $('#orderDetailModal .modal-content').css('left', '0px').css('top', '0px');
        window.getOrderInfoStatus = 0;
        getOrderInfo(param);
        getPriceData(getDate(window.startDate));
    });    
    $('#push_content').on('click', '.order-item', function(e) {
        e.stopPropagation();
        var orderItem = $(this);
        var orderRoomValue = orderItem.data('value');
        var roomId = orderItem.data('room');
        var orderValue = orderItem.data('parent');
        var currentHotel = orderItem.data('hotel');
        var newsPushRelateId = orderItem.closest('.message_list').find('.btn-close').data('relateid');
        var newsPushId = orderItem.closest('.message_list').find('.btn-close').data('pushid');
        var check = orderItem.data('check');
        // showMainLoading();
        // 请求订单数据
        var param = {};
        param.hotel = currentHotel;
        param.order = orderValue;
        var initContent = $('#orderInitContent');
        initContent.data('value', orderRoomValue);
        initContent.data('parent', orderValue);
        initContent.data('roomid', roomId);
        $('#orderDetailModal .modal-content').css('left', '0px').css('top', '0px');
        window.getOrderInfoStatus = 0;
        getOrderInfo(param);
        getPriceData(getDate(window.startDate));
        if(check !== 1){
            ajaxRequest('/Home/NewsPush/saveNews', {
                "hotel": window.currentHotel,
                "newsPushRelateId":newsPushRelateId,
                "newsPushId":newsPushId,
                "type": 1,
            }, 'post', function(data) {
                orderItem.closest('.message_list').removeClass('xiaoxi_color');
            }, function(error) { 
            });            
        }
    });
    $('#orderInitContent').on('click', '.resend-active .usermobile', function(e) {
        e.preventDefault();
        var submitMobile = $(this);
        var parentSubOrderItem = submitMobile.parents('.order-info-item');
        var confirmResult = window.confirm(lang('repunch.1') + submitMobile.text() + lang('repunch.2'));
        if (confirmResult) {
            var param = {};
            param.hotel = window.currentHotel;
            param.order = parentSubOrderItem.data('value');
            param.orderUser = submitMobile.data('orderuser');
            showMainLoading();
            formInlineRight($('#initCheckOut'));
            ajaxRequest('/Home/Order/resendCheckInOrderSMS', param, 'post', function(data) {
                hideMainLoading();
                formInlineTip($('#initCheckOut'), lang('sentSuccessfully'), 1);
                var canGetCard = data.data;
                if (canGetCard === 0) {
                    parentSubOrderItem.removeClass('resend-active').siblings().removeClass('resend-active');
                    parentSubOrderItem.children().removeClass('resend-active');
                    parentSubOrderItem.siblings().children().removeClass('resend-active');
                }
            }, function(data) {
                hideMainLoading();
                if (typeof data.responseJSON == 'undefined') {
                    formInlineTip($('#initCheckOut'), lang('tip.networkPoor'));
                } else if (data.responseJSON.status === 508 || data.responseJSON.status === 507) {
                    parentSubOrderItem.removeClass('resend-active').siblings().removeClass('resend-active');
                    parentSubOrderItem.children().removeClass('resend-active');
                    parentSubOrderItem.siblings().children().removeClass('resend-active');
                    formInlineTip($('#initCheckOut'), data.responseJSON.info, 2);
                } else {
                    formInlineTip($('#initCheckOut'), data.responseJSON.info);
                }
            });
        }
    });
    // 取消订单初始化
    $('#initCancel').on('click', function(e) {
        var initContent = $('#orderInitContent');
        var orderValue = initContent.data('parent');
        var orderRoomValue = initContent.data('value');
        // 请求订单收款以及押金记录
        var param = {};
        param.hotel = window.currentHotel;
        param.order = orderValue;
        ajaxRequest('/Home/Order/getPayHistory', param, 'post', cancelOrderInitSuccess, function(error) {
            hideMainLoading();
        });
        // 初始化除请求记录外的其他信息
        var cancelContent = $('#orderCancelContent');
        var confirmBtn = $('#cancelOrderConfirm');
        confirmBtn.data('parent', orderValue);
        confirmBtn.data('value', orderRoomValue);
        var orderRoomInfo;
        $.each(window.orderDetailInfo.rooms, function(index, orderRoom) {
            if (parseInt(orderRoom.id) == parseInt(orderRoomValue)) {
                // 初始化房间信息
                orderRoomInfo = orderRoom;
                return false;
            }
        });
        var refundRelationTip = $('#relation-refund-tip');
        if (window.orderDetailInfo.rooms.length === 1) {
            refundRelationTip.addClass('hidden');
        } else {
            refundRelationTip.removeClass('hidden');
        }
        // 备注
        cancelContent.find('#cancelOrderRemark').val(window.orderDetailInfo.remark);
        // 退款
        var receiptTotal = parseFloat(parseFloat(window.orderDetailInfo.receipt)-parseFloat(window.orderDetailInfo.otherReceivePrice));
        var depositTotal = parseFloat(window.orderDetailInfo.deposit);
        receiptTotal = receiptTotal > 0 ? receiptTotal : 0;
        cancelContent.find('.refund').html(receiptTotal);
        cancelContent.find('.record').html(depositTotal);
        $('#cancelReceipt').val(receiptTotal);
        $('#cancelDeposit').val(depositTotal);
        var cancelOrderRooms = $('#cancelOrderRooms');
        var userNames = [];
        for (var index in orderRoomInfo.user) {
            if (parseInt(orderRoomInfo.user[index].isdelete) === 1) {
                continue;
            }

            userNames.push(orderRoomInfo.user[index].name);
        }
        userNames = userNames.join(',');
        cancelOrderRooms.find('.username').html(userNames);

        // 计算实住
        var templateEnd = getDate(orderRoomInfo.enddate);
        var nightToEnd = today.getDays(templateEnd);
        if (nightToEnd < 0) {
            var night = today.getDays(getDate(orderRoomInfo.startdate));
        } else {
            var night = templateEnd.getDays(getDate(orderRoomInfo.startdate));
        }

        // 有设置下单时间的订单 计算实住
        if (orderRoomInfo.ismidnightorder) {
            night++;
        }

        cancelOrderRooms.find('.room').html(orderRoomInfo.room);
        cancelOrderRooms.find('.type').html(orderRoomInfo.type);
        cancelOrderRooms.find('.pay').html(orderRoomInfo.pay);
        if(window.edithour){
            cancelOrderRooms.find('.cancelOrderNight').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderLong').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderHour').removeClass('hidden').find('.startdate').html(orderRoomInfo.starttime);
            cancelOrderRooms.find('.cancelOrderHour .hour').html(orderRoomInfo.hour < 0 ? 0 : orderRoomInfo.hour);
        }else if(window.editlong){
            cancelOrderRooms.find('.cancelOrderHour').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderNight').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderLong').removeClass('hidden');
            cancelOrderRooms.find('.cancelOrderLong .night').html(orderRoomInfo.night < 0 ? 0 : orderRoomInfo.night);
            cancelOrderRooms.find('.cancelOrderLong .startdate').html(getDate(orderRoomInfo.startdate).customFormat(lang('tip.date')));
            cancelOrderRooms.find('.cancelOrderLong .enddate').html(getDate(orderRoomInfo.enddate).customFormat(lang('tip.date')));
        }else{
            cancelOrderRooms.find('.cancelOrderHour').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderLong').addClass('hidden');
            cancelOrderRooms.find('.cancelOrderNight').removeClass('hidden');
            cancelOrderRooms.find('.cancelOrderNight .night').html(night < 0 ? 0 : night);
            cancelOrderRooms.find('.cancelOrderNight .startdate').html(getDate(orderRoomInfo.startdate).customFormat(lang('tip.date')));
            cancelOrderRooms.find('.cancelOrderNight .enddate').html(getDate(orderRoomInfo.enddate).customFormat(lang('tip.date')));
        }        
        initContent.addClass('hidden');
        cancelContent.removeClass('hidden');
    });
    // 取消订单自动校验
    $('#orderCancelContent').inputValidate({
        submit: {
            query: '#cancelOrderConfirm'
        },
        inputs: [{
            query: '#cancelReceipt',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.money')
        }, {
            query: '#cancelDeposit',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.cash')
        }, {
            query: '#cancelOrderRemark',
            regexp: window.commonRegexp.nameLength255,
            required: false,
            message: lang('tip.remark')
        }]
    });
    $('#cancelOrderConfirm').on('successSubmit.amos.inputValidate', function(e) {
        var $me = $(this),
            receipt = $('#cancelReceipt').val().trim(),
            deposit = $('#cancelDeposit').val().trim(),
            remark = $('#cancelOrderRemark').val().trim(),
            param = {},
            initContent = $('#orderInitContent'),
            operating = initContent.data('parent'),
            operatingSub = initContent.data('value');
        if (receipt != '') {
            if ($('#cancelReceiptType').data('value') == 1 && receipt != 0) {
                receipt = '-' + receipt;
            }
            param.receipt = receipt;
            param.receiptpay = $('#cancelReceiptPay').data('value');
            param.receiptCurrencyId = $('#cancelReceiptCurrencyType').data('value');
        }
        if (deposit != '') {
            param.deposit = deposit === 0 ? 0 : '-' + deposit;
            param.depositpay = $('#cancelDepositPay').data('value');
            param.depositCurrencyId = $('#cancelDepositCurrencyType').data('value');
        }
        param.remark = remark;
        param.hotel = window.currentHotel;
        param.order = operating;
        param.suborder = operatingSub;
        ajaxRequest('/Home/Order/cancel', param, 'post', null, null, $me);
    });
    // 办理入住   
    $('#initCheckIn').on('click', function() {
        var initContent = $('#orderInitContent');
        var orderValue = initContent.data('parent');
        var orderRoomValue = initContent.data('value');
        var confirmBtn = $('#checkInConfirm');
        confirmBtn.data('parent', orderValue);
        confirmBtn.data('value', orderRoomValue);
        var checkInContent = $('#orderCheckInContent');
        var orderDetail = window.orderDetailInfo;
        // 加入可入住的房间选项
        var templateOriginal = $('#templateCheckInItem');
        var checkInUsers = $('#checkInUsers');
        var userHTML = '';
        var checkableStatus = [
            window.orderStatus.booked,
            window.orderStatus.paied
        ];
        $.each(orderDetail.rooms, function(index, orderRoomInfo) {
            // 日期跨度经过今天，且状态正确的情况
            if ($.inArray(orderRoomInfo.status, checkableStatus) !== -1 && getDate(orderRoomInfo.startdate).getDays(today) <= 0 && getDate(orderRoomInfo.enddate).getDays(today) >= 0) {
                var template = $(templateOriginal.clone().html());
                template.attr('value', orderRoomInfo.id);
                template.find('.pay').html(orderRoomInfo.pay);
                template.find('.room').html(orderRoomInfo.room);
                template.find('.type').html(orderRoomInfo.type);
                if(parseFloat(orderRoomInfo.hour)>0){
                    template.find('.checkInItem-hour').removeClass('hidden').find('.hour').html(orderRoomInfo.hour);
                    template.find('.startdate').html(orderRoomInfo.starttime);             
                }else{
                    template.find('.checkInItem-night').removeClass('hidden').find('.night').html(orderRoomInfo.night);
                    template.find('.startdate').html(getDate(orderRoomInfo.startdate).customFormat(lang('tip.date')));
                    template.find('.enddate').html(getDate(orderRoomInfo.enddate).customFormat(lang('tip.date')));                    
                }
                for (var i = 0; i < orderRoomInfo.user.length; i++) {
                    if (parseInt(orderRoomInfo.user[i].isdelete) === 1) {
                        continue;
                    }
                    var templateCheckinUserItem = $($('#templateCheckInUserItem').clone().html());
                    templateCheckinUserItem.find('.checkInOrderUserName').attr('value', orderRoomInfo.user[i].name);
                    templateCheckinUserItem.find('.areaCodeValue').text(orderRoomInfo.user[i].areaCode);
                    templateCheckinUserItem.find('.checkInOrderUserMobile').attr('value', orderRoomInfo.user[i].mobile);
                    templateCheckinUserItem.find('.checkInOrderUserID').attr('value', orderRoomInfo.user[i].identity);
                    templateCheckinUserItem.attr('data-orderuser', orderRoomInfo.user[i].orderUser);
                    template.find('tbody').append(templateCheckinUserItem);
                }
                userHTML += template.prop('outerHTML');
            }
        });
        checkInUsers.html(userHTML);
        var orderUserMobile = $('#orderCheckInContent .checkInOrderUserMobile');
        for(var i=0;i<orderUserMobile.length;i++){
            var value = orderUserMobile.eq(i).val();
            if(value.indexOf("***")>=0){
                orderUserMobile.eq(i).attr('data-star','1');
            }else{
                orderUserMobile.eq(i).attr('data-star','0');
            }
        }
        orderUserMobile.change(function (e) {           
            var value = $(this).val();
            if(value.indexOf("*")>=0){
                $(this).val('');
            }else{
                $(this).attr('data-star','0');
            }
        });
        // 总费用，已收款，待付款
        checkInContent.find('.total').html(orderDetail.pay);
        checkInContent.find('.receipt').html(orderDetail.receipt);
        checkInContent.find('.deposit').html(orderDetail.deposit);
        // 重置收款input 提交按钮
        $('#checkInReceipt').val('');
        $('#checkInDeposit').val('');
        formInlineRight($('#checkInConfirm'));
        var overdue = (parseFloat(orderDetail.pay) - parseFloat(orderDetail.receipt)).toFixed(2);
        overdue = overdue < 0 ? 0 : overdue;
        checkInContent.find('.overdue').html(overdue);
        $('#checkInOrderReceive').val(overdue);
        $('#checkInRemark').val(orderDetail.remark);
        initContent.addClass('hidden');
        checkInContent.removeClass('hidden');
    });
    // 办理入住自动校验
    var roleCheck = $('#orderCheckInContent').attr('data-role');
    if(roleCheck == 1){
        $('#orderCheckInContent').inputValidate({
            submit: {
                query: '#checkInConfirm'
            },
            inputs: [{
                query: '#checkInReceipt',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.gathering')
            }, {
                query: '#checkInDeposit',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.cash')
            }, {
                query: '#checkInRemark',
                regexp: window.commonRegexp.nameLength255,
                required: false,
                message: lang('tip.remark')
            }, {
                query: '.checkInOrderUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.checkInOrderUserMobile',
                required: false,
                regexp: window.commonRegexp.mobile,
                message: lang('tip.phoneForma')
            }]
        });        
    }else{
        $('#orderCheckInContent').inputValidate({
            submit: {
                query: '#checkInConfirm'
            },
            inputs: [{
                query: '#checkInReceipt',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.gathering')
            }, {
                query: '#checkInDeposit',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.cash')
            }, {
                query: '#checkInRemark',
                regexp: window.commonRegexp.nameLength255,
                required: false,
                message: lang('tip.remark')
            }, {
                query: '.checkInOrderUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }]
        });        
    }
    var getCheckInParams = function(){
        $initContent = $('#orderInitContent'),
        operating = $initContent.data('parent'),
        param = {
            hotel: window.currentHotel,
            order: operating,
            data: []
        },
        receipt = $('#checkInReceipt').val().trim(),
        deposit = $('#checkInDeposit').val().trim(),
        remark = $('#checkInRemark').val().trim();
        $('#checkInUsers .addOrderTable').each(function(e) {
            var orderRoomData = {};
            var me = $(this);
            orderRoomData.value = me.attr('value');
            orderRoomData.users = [];
            me.find('.addOrderUserTr').each(function() {
                var orderUserTr = $(this);
                var orderUserItem = {
                    name: orderUserTr.find('.checkInOrderUserName').val().trim(),
                    orderUser: orderUserTr.data('orderuser'),
                };
                var isStar =  $(this).find('.checkInOrderUserMobile').attr('data-star');
                if(isStar == '1'){
                    var mobile = '';
                }else{
                    var mobile = orderUserTr.find('.checkInOrderUserMobile').val().trim();
                }       
                var identity = orderUserTr.find('.checkInOrderUserID').val().trim();
                if (mobile != '') {
                    orderUserItem.mobile = mobile;
                }
                if (identity != '') {
                    if(identity.indexOf("*")<=0){
                        orderUserItem.identity = identity;
                    }
                }
                var areaCode = orderUserTr.find('.areaCodeValue').text().trim();
                orderUserItem.areaCode = areaCode;
                orderRoomData.users.push(orderUserItem);
            });
            param.data.push(orderRoomData);
        });
        param.data = JSON.stringify(param.data);
        if (receipt != '' && receipt != 0) {
            param.receipt = receipt;
            param.receiptpay = $('#checkInReceiptPay').data('value');
            param.receiptCurrencyId = $('#checkInReceiptCurrencyType').data('value');
        }
        if (deposit != '' && deposit != 0) {
            param.deposit = deposit;
            param.depositpay = $('#checkInDepositPay').data('value');
            param.depositCurrencyId = $('#checkInDepositCurrencyType').data('value');
        }
        param.remark = remark;  
        return param;
    };      
    // 办理入住提交请求
    var checkInOrderError = function(data){
        var submitBtn = $('#checkInConfirm');
        if(data.responseJSON.status == 308){
            $('#checkoutDirtyModal').show();
            var dirtyTip = $('#checkoutDirtyModal .modal-body');
            dirtyTip.find('li').remove();
            var infoStatus =  data.responseJSON.data.orderRoomInfos;
            var infoDirty =  data.responseJSON.data.roomInfos;
            var vipCard = data.responseJSON.data.vipCard;
            if(infoDirty){
                for(var i = 0; i < infoDirty.length; i++) {
                    dirtyTip.append($('<li/>').text(infoDirty[i].roomName + lang('Dirty.1')));
                }
            }
            if(infoStatus){
                for(var i = 0; i < infoStatus.length; i++) {
                    dirtyTip.append($('<li/>').text(infoStatus[i].roomName + lang('Dirty.2')));
                }       
            }
        }
        $('#cancelEnterBtnL').on('click',function(){
            $('#checkoutDirtyModal').hide();
        });
        $('#confirmEnterBtnL').click(function(){
            showMainLoading();
            $('#checkoutDirtyModal').hide();
            var editBlrzButton = $('#checkInConfirm');
            var param = getCheckInParams();
            param.checkIn = 0;
            if(vipCard){
                param.vipCard = vipCard;
            }
            ajaxRequest('/Home/Order/checkin', param, 'post', function(){
                editBlrzButton.trigger('afterBlrzCommit');
                ajaxRequest('/Home/Order/getOrder',  {
                    'hotel':window.currentHotel,
                    'order':param.order,
                }, 'post', initOrderInfoSuccess, function(error) {
                    hideMainLoading();
                });
            },function(data){
                formInlineTip(submitBtn,data.responseJSON.info);
                hideMainLoading();
            },submitBtn);
        }); 
        if(data.responseJSON.status == 502){
            formInlineTip(submitBtn,data.responseJSON.info);
        }     
    }
    $('#checkInConfirm').on('successSubmit.amos.inputValidate', function(e) {        
        var editBlrzButton = $(this);
        var submitBtn = $(this),
        param = getCheckInParams();
        param.checkIn = 1;
        if(!getRoomVerification(7,param,$(this))){
            return false;
        }           
        ajaxRequest('/Home/Order/checkin', param, 'post', function(){
            editBlrzButton.trigger('afterBlrzCommit');
            ajaxRequest('/Home/Order/getOrder', {
                'hotel':window.currentHotel,
                'order':param.order,
            }, 'post', initOrderInfoSuccess, function(error) {
                hideMainLoading();
            });
        },checkInOrderError,submitBtn);
    });
    // 修改订单触发
    var initEdit = function(){
        window.discount = "";
        window.discountrule = "";
        var initContent = $('#orderInitContent');
        var orderValue = initContent.data('parent');
        var orderRoomValue = initContent.data('value');
        var confirmBtn = $('#editOrderConfirm');
        confirmBtn.data('parent', orderValue);
        confirmBtn.data('value', orderRoomValue);
        var editContent = $('#orderEditContent');
        var orderDetail = window.orderDetailInfo;
        // 渠道选择
        editContent.find('.editOrderChannelMenu li[data-value="' + orderDetail.channelid + '"]').addClass('active').siblings().removeClass('active');
        editContent.find('.editOrderChannel').data('value', orderDetail.channelid);
        editContent.find('.editOrderChannel .info').html(orderDetail.channelName);
        // 加入可入住的房间选项
        var editOrderRoom = $('#editOrderRoom');
        var orderRooms = '';
        var isAllCancel = true;
        $.each(orderDetail.rooms, function(index, orderRoomInfo) {
            var isCancelled = orderRoomInfo.status === window.orderStatus.cancelled;
            if (isAllCancel && !isCancelled) {
                isAllCancel = false;
            }
            var selectedDateFormat = orderRoomInfo.startdate;
            var editable = !isCancelled;
            var removeAble = editable;
            if (index === 0) {
                removeAble = false;
            }
            // 已退房的不能取消
            if (orderRoomInfo.status == window.orderStatus.checkout) {
                removeAble = false;
            }
            if(window.edithour){
                orderRooms += createEditOrderHourRoomTemplate(selectedDateFormat, orderRoomInfo, removeAble, editable);
            }else if(window.editlong){
                orderRooms += createEditOrderLongRoomTemplate(selectedDateFormat, orderRoomInfo, removeAble, editable);
            }else{
                orderRooms += createEditOrderRoomTemplate(selectedDateFormat, orderRoomInfo, removeAble, editable);
            }
            
        });
        editOrderRoom.html(orderRooms);
        //退款记录
        var receiptAppend = $('#orderEditContent .receiptAppend');
        var refundAppend = $('#orderEditContent .refundAppend');
        receiptAppend.html('');
        refundAppend.html('');
        var payHistory = [lang('type.receipt'), lang('type.cash'), lang('type.refund'), lang('type.returnDeposit')];
        var payHTML = '';
        var refundHTML = '';    
        var payReceipt = 0.00;
        var refundReceipt = 0.00;
        $.each(orderDetail.payHistory.receivedInfo, function(index, receivedInfo) {
            var payTemplate = $($('#templateOrderPayRefund').clone().html());
            payTemplate.attr('data-id',receivedInfo.id);
            payTemplate.find('.receipt-or-refund').html(payHistory[receivedInfo.type]).attr('data-value',receivedInfo.type);
            payTemplate.find('.changeOrderReceiveIsDepositMenu .info').html(payHistory[receivedInfo.type]);
            payTemplate.find('.changeOrderReceiveIsDepositMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.type);            
            payTemplate.find('.changeOrderReceiveIsDepositMenu [data-value='+receivedInfo.type+']').addClass('active');
            payTemplate.find('.receiptPayStyle').html(receivedInfo.name).attr('data-value',receivedInfo.hotelPayId);
            payTemplate.find('.changeOrderPayStyleMenu .info').html(receivedInfo.name);
            payTemplate.find('.changeOrderPayStyleMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.hotelPayId);            
            payTemplate.find('.changeOrderPayStyleMenu [data-value='+receivedInfo.hotelPayId+']').addClass('active');
            payTemplate.find('.edit-currency').html(receivedInfo.currencyName).attr('data-value',receivedInfo.currencyId);
            payTemplate.find('.changeOrderCurrencyMenu .info').html(receivedInfo.currencyName);
            payTemplate.find('.changeOrderCurrencyMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.currencyId);            
            payTemplate.find('.changeOrderCurrencyMenu [data-value='+receivedInfo.currencyId+']').addClass('active');
            var originalPay = receivedInfo.pay;
            if(parseFloat(receivedInfo.transBeforePay) > 0){
                originalPay = receivedInfo.transBeforePay;
            }
            payTemplate.find('.refund-receipt').html(originalPay);
            payTemplate.find('.receipt-edit-operation').attr('value',originalPay);
            if(receivedInfo.name == lang('recharge.8')){
                payTemplate.find('.refund-receipt-operation').addClass('disabled');
            }
            payHTML += payTemplate.prop('outerHTML');
            payReceipt += parseFloat(receivedInfo.pay);
        });       
        $.each(orderDetail.payHistory.refundInfo, function(index, refundInfo) {
            var RefundTemplate = $($('#templateOrderPayRefund').clone().html());
            RefundTemplate.attr('data-id',refundInfo.id);
            RefundTemplate.find('.receipt-or-refund').html(payHistory[refundInfo.type]).attr('data-value',refundInfo.type);
            RefundTemplate.find('.changeOrderReceiveIsDepositMenu .info').html(payHistory[refundInfo.type]);
            RefundTemplate.find('.changeOrderReceiveIsDepositMenu [data-toggle="dropdown"]').attr('data-value',refundInfo.type);           
            RefundTemplate.find('.changeOrderReceiveIsDepositMenu [data-value='+refundInfo.type+']').addClass('active');
            RefundTemplate.find('.receiptPayStyle').html(refundInfo.name).attr('data-value',refundInfo.hotelPayId);
            RefundTemplate.find('.changeOrderPayStyleMenu .info').html(refundInfo.name);
            RefundTemplate.find('.changeOrderPayStyleMenu [data-toggle="dropdown"]').attr('data-value',refundInfo.hotelPayId);            
            RefundTemplate.find('.changeOrderPayStyleMenu [data-value='+refundInfo.hotelPayId+']').addClass('active');
            RefundTemplate.find('.edit-currency').html(refundInfo.currencyName).attr('data-value',refundInfo.currencyId);
            RefundTemplate.find('.changeOrderCurrencyMenu .info').html(refundInfo.currencyName);
            RefundTemplate.find('.changeOrderCurrencyMenu [data-toggle="dropdown"]').attr('data-value',refundInfo.currencyId);            
            RefundTemplate.find('.changeOrderCurrencyMenu [data-value='+refundInfo.currencyId+']').addClass('active');  
            var originalPay = refundInfo.pay;
            if(parseFloat(refundInfo.transBeforePay) > 0){
                originalPay = refundInfo.transBeforePay;
            }
            RefundTemplate.find('.refund-receipt').html(originalPay);
            RefundTemplate.find('.receipt-edit-operation').attr('value',originalPay);
            if(refundInfo.name == lang('recharge.8')){
                RefundTemplate.find('.refund-receipt-operation').addClass('disabled');
            }
            refundHTML += RefundTemplate.prop('outerHTML');
            refundReceipt += parseFloat(refundInfo.pay);
        });        
        receiptAppend.append(payHTML);
        refundAppend.append(refundHTML);
        if(orderDetail.payHistory.receivedInfo.length < 1){
            $('.receiptAlerdy').addClass('hidden');
        }else{
            $('.receiptAlerdy').removeClass('hidden');
        }
        if(orderDetail.payHistory.refundInfo.length < 1){
            $('.refundAlerdy').addClass('hidden');
        }else{
            $('.refundAlerdy').removeClass('hidden');
        }        
        
        //其他消费
        var receiptAppendProject = $('#orderEditContent .receiptAppendProject');
        var refundAppendProject = $('#orderEditContent .refundAppendProject');
        receiptAppendProject.html('');
        refundAppendProject.html('');
        var payProjectHTML = '';
        var refundProjectHTML = '';    
        var payReceiptProject = 0.00;
        var refundReceiptProject = 0.00;
        $.each(orderDetail.payHistory.otherReceivedInfo, function(index, receivedInfo) {
            var payTemplate = $($('#templateOrderPayRefund').clone().html());
            payTemplate.attr('data-id',receivedInfo.id);
            payTemplate.find('.changeOrderReceiveIsDepositMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.type);            
            payTemplate.find('.changeOrderReceiveIsDepositMenu [data-value='+receivedInfo.type+']').addClass('active');
            payTemplate.find('.receiptPayStyle').html(receivedInfo.name).attr('data-value',receivedInfo.hotelPayId);
            payTemplate.find('.changeOrderPayStyleMenu .info').html(receivedInfo.name);
            payTemplate.find('.changeOrderPayStyleMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.hotelPayId);            
            payTemplate.find('.changeOrderPayStyleMenu [data-value='+receivedInfo.hotelPayId+']').addClass('active');
            payTemplate.find('.edit-currency').html(receivedInfo.currencyName).attr('data-value',receivedInfo.currencyId);
            payTemplate.find('.changeOrderCurrencyMenu .info').html(receivedInfo.currencyName);
            payTemplate.find('.changeOrderCurrencyMenu [data-toggle="dropdown"]').attr('data-value',receivedInfo.currencyId);            
            payTemplate.find('.changeOrderCurrencyMenu [data-value='+receivedInfo.currencyId+']').addClass('active');
            var originalPay = receivedInfo.pay;
            if(parseFloat(receivedInfo.transBeforePay) > 0){
                originalPay = receivedInfo.transBeforePay;
            }            
            payTemplate.find('.refund-receipt').html(originalPay);
            payTemplate.find('.receipt-edit-operation').attr('value',originalPay);
            if(receivedInfo.name == lang('recharge.8')){
                payTemplate.find('.refund-receipt-operation').addClass('disabled');
            }
            payTemplate.find('.receipt-or-refund').html(receivedInfo.otherCostName).attr('data-value',receivedInfo.type);
            payTemplate.find('.changeOrderReceiveIsDepositMenu .info').html(receivedInfo.otherCostName);
            payTemplate.find('.other-expense-btn').addClass('active').siblings('li').removeClass('active');
            payTemplate.find('.other-expense-content').removeClass('hidden');
            payTemplate.find('.other-expense-content .list').each(function(){
                if($(this).data('cost') == receivedInfo.type){
                    $(this).addClass('active').siblings('.list').removeClass('active');
                }
            })
            payProjectHTML += payTemplate.prop('outerHTML');
            payReceiptProject += parseFloat(receivedInfo.pay);
        });              
        receiptAppendProject.append(payProjectHTML);
        if(orderDetail.payHistory.otherReceivedInfo.length < 1){
            $('.receiptAlerdyProject').addClass('hidden');
        }else{
            $('.receiptAlerdyProject').removeClass('hidden');
        }      
        
        // 总费用，已收款，待付款
        window.minusPrice = orderDetail.rooms[0].minusprice;
        if(parseFloat(orderDetail.discountrule)>0){
            window.discount = orderDetail.discount;
            window.discountrule = orderDetail.discountrule;
            editContent.find('.privilege').html(lang('privilege')+window.symbols+orderDetail.pay);
            editContent.find('.total').html(orderDetail.orig);
        }else{
            window.discount = "";
            window.discountrule = "";
            editContent.find('.total').html(orderDetail.pay);
        }
        editContent.find('.deposit').html(orderDetail.deposit);
        var overdue = (parseFloat(orderDetail.pay) - parseFloat(orderDetail.receipt)).toFixed(2);
        overdue = overdue < 0 ? 0 : overdue;
        editContent.find('.overdue').html(overdue);
        editContent.find('.payReceiptProject').html(payReceiptProject.toFixed(2));
        editContent.find('.payReceipt').html(payReceipt.toFixed(2));
        editContent.find('.refundReceipt').html(refundReceipt.toFixed(2));
        if (isAllCancel) {
            $('#editOrderReceive').html('');
            $('#editOrderRoomAdd').addClass('hidden');
            $('#editOrderReceiveAdd').addClass('hidden');
        } else {
            // 重置收款
            $('#editOrderReceive').html('');
            $('#editOrderRoomAdd').removeClass('hidden');
            $('#editOrderReceiveAdd').removeClass('hidden');
        }
        // 重置提交按钮状态
        formInlineRight($('#editOrderConfirm'));
        // 备注
        $('#editOrderRemark').val(orderDetail.remark);
        initContent.addClass('hidden');
        editContent.removeClass('hidden');
        if(window.edithour){
            calculateEditHourContentTotal();
        }else if(window.editlong){
            calculateEditLongContentTotal();
        }else{
            calculateEditContentTotal();
        } 
        if(orderDetail.trueMobile){
            window.trueMobile = orderDetail.trueMobile;
        }
    };
    //修改收款押金
    $('#orderEditContent').on('click','.refund-receipt-operation',function(){
       var btn = $(this);
       var editOrderReceiveModule = btn.closest('.editOrderReceiveModule');
       var btnTr = btn.closest('tr');
       if(!btn.hasClass('hidden')){
           btn.addClass('hidden');
           btn.next('.affirm-operation').removeClass('hidden');
           btnTr.find('.refund-receipt').addClass('hidden');
           btnTr.find('.receipt-edit-operation').removeClass('hidden');
           btnTr.find('.receipt-or-refund').addClass('hidden');
           btnTr.find('.receiptPayStyle').addClass('hidden');
           btnTr.find('.edit-currency').addClass('hidden');
           btnTr.find('.changeOrderReceiveIsDepositMenu').removeClass('hidden');
           btnTr.find('.changeOrderPayStyleMenu').removeClass('hidden');
           btnTr.find('.changeOrderCurrencyMenu').removeClass('hidden');
           if(editOrderReceiveModule.hasClass('receiptAlerdy')||editOrderReceiveModule.hasClass('receiptAlerdyProject')){
               btnTr.find('.receive-content').removeClass('hidden');
               btnTr.find('.retreat-content').addClass('hidden');
           }else{
               btnTr.find('.retreat-content').removeClass('hidden');
               btnTr.find('.receive-content').addClass('hidden');
           }
       }
    });
    $('#orderEditContent').on('click','.affirm-operation',function(){
        var btn = $(this);
        var btnTr = btn.closest('tr');
        var value =  btnTr.find('.receipt-edit-operation').val();
        var dropdownReceive =  btnTr.find('.changeOrderReceiveIsDepositMenu [data-toggle="dropdown"]');
        var dropdownStyles =  btnTr.find('.changeOrderPayStyleMenu [data-toggle="dropdown"]');
        var currencyStyles =  btnTr.find('.changeOrderCurrencyMenu [data-toggle="dropdown"]');
        $('.form-group').removeClass('has-error');
        if(!window.commonRegexp.roomTypePrice.test(value)){
            formInlineTip($('#editOrderConfirm'), lang('constant.sum'), 0);
            btnTr.find('.receipt-edit-operation').addClass('tip-color');
            return false;
        }else{
            btnTr.find('.receipt-edit-operation').removeClass('tip-color');
        };
        $('.editOrderReceiveModule').find('.receipt-edit-operation').each(function() {
            if($(this).hasClass('tip-color')){
                formInlineTip($('#editOrderConfirm'), lang('constant.sum'), 0);
            }
        });         
        if(!btn.hasClass('hidden')){
           btn.addClass('hidden');
           btn.prev('.refund-receipt-operation').removeClass('hidden');
           btnTr.find('.receipt-edit-operation').addClass('hidden');
           btnTr.find('.refund-receipt').removeClass('hidden').text(value);
           btnTr.find('.changeOrderReceiveIsDepositMenu').addClass('hidden');
           btnTr.find('.changeOrderPayStyleMenu').addClass('hidden');
           btnTr.find('.changeOrderCurrencyMenu').addClass('hidden');
           btnTr.find('.receipt-or-refund').removeClass('hidden').text(dropdownReceive.text()).attr('data-value',dropdownReceive.data('value'));
           btnTr.find('.receiptPayStyle').removeClass('hidden').text(dropdownStyles.text()).attr('data-value',dropdownStyles.data('value'));
           btnTr.find('.edit-currency').removeClass('hidden').text(currencyStyles.text()).attr('data-value',currencyStyles.data('value'));
        };
    });       

    $('#initEdit').on('click', function() {
  		initEdit();
        var orderUserMobile = $('#editOrderRoom .orderUserMobile');
        for(var i=0;i<orderUserMobile.length;i++){
            var value = orderUserMobile.eq(i).val();
            if(value.indexOf("***")>=0){
                orderUserMobile.eq(i).attr('data-star','1');
            }else{
                orderUserMobile.eq(i).attr('data-star','0');
            }
        }
        orderUserMobile.change(function (e) {           
            var value = $(this).val();
            if(value.indexOf("*")>=0){
                $(this).val('');
            }else{
                $(this).attr('data-star','0');
            }
        });
        var orderHourUserMobile = $('#editOrderRoom .orderHourUserMobile');
        for(var i=0;i<orderHourUserMobile.length;i++){
            var value = orderHourUserMobile.eq(i).val();
            if(value.indexOf("***")>=0){
                orderHourUserMobile.eq(i).attr('data-star','1');
            }else{
                orderHourUserMobile.eq(i).attr('data-star','0');
            }
        }
        orderHourUserMobile.change(function (e) {           
            var value = $(this).val();
            if(value.indexOf("*")>=0){
                $(this).val('');
            }else{
                $(this).attr('data-star','0');
            }
        });     
        var orderLongUserMobile = $('#editOrderRoom .orderLongUserMobile');
        for(var i=0;i<orderLongUserMobile.length;i++){
            var value = orderLongUserMobile.eq(i).val();
            if(value.indexOf("***")>=0){
                orderLongUserMobile.eq(i).attr('data-star','1');
            }else{
                orderLongUserMobile.eq(i).attr('data-star','0');
            }
        }
        orderLongUserMobile.change(function (e) {           
            var value = $(this).val();
            if(value.indexOf("*")>=0){
                $(this).val('');
            }else{
                $(this).attr('data-star','0');
            }
        });     
    });
    //修改订单 -- 查看收款
    $('#orderEditContent').on('click', '.revenue-expenditure', function(e) {
        e.preventDefault();
        var trigger = $(this).find('.caret');
        if (trigger.hasClass('revert')) {
            $(this).next('.payStyle').addClass('hidden');
        } else {
            $(this).next('.payStyle').removeClass('hidden');
        }
        trigger.toggleClass('revert');
    });    
 
    // 修改订单 -- 金额变化
    var getCouponPrice = function(tempPrice){
        //优惠券
        var charityprice = parseFloat(window.orderDetailInfo.charityprice);
        var couponType = window.orderDetailInfo.couponType;
        var couponpPrice = parseInt(window.orderDetailInfo.couponpPrice);
        var couponRule = parseInt(window.orderDetailInfo.couponRule);
        if(couponType == 1){
            if(tempPrice >= couponpPrice){
                tempPrice = tempPrice - parseFloat(charityprice) - couponRule + parseFloat(charityprice);
            }
        }else if(couponType == 2){
            if(tempPrice >= couponpPrice){
                tempPrice = parseFloat((tempPrice - charityprice)*100*couponRule/1000) + parseFloat(charityprice);
            }
        }        
        if(couponType == 1){
            $('#orderEditContent').find('.coupon-type').html(lang('Coupon.01'));
            $('#orderEditContent').find('.request-money').html(lang('Coupon.07')+couponpPrice+lang('Coupon.08')+window.symbols+couponRule);
        }else if(couponType == 2){
            $('#orderEditContent').find('.coupon-type').html(lang('Coupon.02'));
            $('#orderEditContent').find('.request-money').html(lang('Coupon.07')+couponpPrice+lang('Coupon.10')+couponRule+lang('Coupon.11'));
        }else{
            $('#orderEditContent').find('.coupon-type').html('');
            $('#orderEditContent').find('.request-money').html('');
        }    
        return tempPrice;
    }
    var calculateEditContentTotal = function(){
        var total = 0;
        var privilege = 0;
        var reducePrice = 0;
        var otherTotal = 0;
        var deposit = 0;
        var otherPrice = 0;
        var otherReceivePrice = parseFloat(window.orderDetailInfo.otherReceivePrice);
        var otherUncollectePrice = parseFloat(window.orderDetailInfo.otherUncollectePrice);
        otherTotal = parseFloat(otherReceivePrice+otherUncollectePrice);
        var receipt = parseFloat(window.orderDetailInfo.receipt);
        var charityprice = window.orderDetailInfo.charityprice;
        $('#editOrderRoom .addOrderPrice').each(function(){       
            var isDisabled = $(this).prop("disabled");
            if(!isDisabled){
                total += parseFloat($(this).val());
                reducePrice += parseFloat(window.discountrule)*parseInt($(this).closest('.addOrderTableRoom').find('.nights .info').text());
            };
        });
        var receivearr = [];      
        $('#editOrderReceive .addOrderReceiveTr').each(function(){
            var isDeposit = $(this).find('.addOrderReceiveIsDeposit').data('value');
            var value = parseFloat($(this).find('.addOrderReceive').val());
            var type = $(this).find('.addOrderReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });          
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            if(data.data.transData){
                $.each(data.data.transData, function (key, value) {
                    var isDeposit = value.isDeposit;
                    var value = parseFloat(value.value);
                    var type = value.type;
                    value = value > 0 ? value : 0;
                    if (isDeposit == 1) {
                        deposit += value;
                    } else if(isDeposit == 0) {
                        receipt += value;
                    }else{
                        if(type !== 0){
                            otherPrice += value;
                        }
                        otherTotal += value;
                    }
                });                 
            }
            if(parseFloat(window.discountrule)>0){ 
                if(parseFloat(window.minusPrice)>0){
                    $('#orderEditContent').find('.privilege').html(lang('concession')+window.symbols+ parseFloat(window.minusPrice).toFixed(2));
                    privilege = parseFloat(total)-parseFloat(charityprice)-parseFloat(window.minusPrice)+parseFloat(charityprice);
                    privilege = getCouponPrice(privilege);
                    if(privilege<0){
                        privilege = 0;
                    }
                }else{
                    if(parseInt(window.discount) == 0){
                        privilege = parseFloat(parseFloat(total)-parseFloat(charityprice))*window.discountrule*100/1000+parseFloat(charityprice);
                    }else{
                        privilege = parseFloat(total)-parseFloat(charityprice)-reducePrice+parseFloat(charityprice);
                    };
                    privilege = getCouponPrice(privilege);
                    if(privilege<0){
                        privilege = 0;
                    }
                    $('#orderEditContent').find('.privilege').html(lang('privilege')+window.symbols+ parseFloat(privilege+otherTotal).toFixed(2));                
                }
            }else{
                if(parseFloat(window.minusPrice)>0){
                    $('#orderEditContent').find('.privilege').html(lang('concession')+window.symbols+ parseFloat(window.minusPrice).toFixed(2));
                    privilege = parseFloat(total)-parseFloat(charityprice)-parseFloat(window.minusPrice)+parseFloat(charityprice);
                    privilege = getCouponPrice(privilege);
                    if(privilege<0){
                        privilege = 0;
                    }
                }else{
                    $('#orderEditContent').find('.privilege').html('');
                    privilege = total;
                    privilege = getCouponPrice(privilege);
                }
            }   
            var orderTotal = otherTotal+privilege;
            var overdue = orderTotal - receipt - otherPrice;
            overdue = overdue < 0 ? 0 : overdue;
            $('#orderEditContent').find('.otherTotal').html(otherTotal.toFixed(2));
            $('#orderEditContent').find('.total').html(total.toFixed(2));
            $('#orderEditContent').find('.receipt').html(receipt.toFixed(2));
            $('#orderEditContent').find('.deposit').html(deposit.toFixed(2));
            $('#orderEditContent').find('.overdue').html(overdue.toFixed(2));
            $('#orderEditContent').find('.order-total').html(parseFloat(total + otherTotal).toFixed(2));            
        }, null);             
    };    
    
    // 钟点房修改订单 -- 金额变化
    var calculateEditHourContentTotal = function(){
        var total = 0;
        var privilege = 0;
        var reducePrice = 0;
        var otherTotal = 0;
        var deposit = 0;
        var otherPrice = 0;
        var otherReceivePrice = parseFloat(window.orderDetailInfo.otherReceivePrice);
        var otherUncollectePrice = parseFloat(window.orderDetailInfo.otherUncollectePrice);
        otherTotal = parseFloat(otherReceivePrice+otherUncollectePrice);
        var receipt = parseFloat(window.orderDetailInfo.receipt);
        var charityprice = window.orderDetailInfo.charityprice;
        $('#editOrderRoom .addOrderHourPrice').each(function(){       
            var isDisabled = $(this).prop("disabled");
            if(!isDisabled){
                total += parseFloat($(this).val());
                reducePrice += parseFloat(window.discountrule);
            };
        });
        var receivearr = [];  
        $('#editOrderReceive .addOrderHourReceiveTr').each(function(){
            var isDeposit = $(this).find('.addOrderHourReceiveIsDeposit').data('value');
            var value = parseFloat($(this).find('.addOrderHourReceive').val());
            var type = $(this).find('.addOrderHourReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyHourType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });                
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            if(data.data.transData){
                $.each(data.data.transData, function (key, value) {
                    var isDeposit = value.isDeposit;
                    var value = parseFloat(value.value);
                    var type = value.type;
                    value = value > 0 ? value : 0;
                    if (isDeposit == 1) {
                        deposit += value;
                    } else if(isDeposit == 0) {
                        receipt += value;
                    } else{
                        if(type !== 0){
                            otherPrice += value;
                        }
                        otherTotal += value;
                    }
                });
            };       
            if(parseFloat(window.discountrule)>0){ 
                if(parseInt(window.discount) == 0){
                    privilege =  parseFloat(total-parseFloat(charityprice))*window.discountrule*100/1000;
                }else{
                    privilege = parseFloat(total)-parseFloat(charityprice)-reducePrice+parseFloat(charityprice);
                } 
                if(privilege<0){
                    privilege = 0;
                }
                $('#orderEditContent').find('.privilege').html(lang('privilege')+window.symbols+parseFloat(privilege+otherTotal).toFixed(2));
            }else{
                $('#orderEditContent').find('.privilege').html('');
                privilege = total;
            }        
            var orderTotal = otherTotal+privilege;
            var overdue = orderTotal - receipt - otherPrice;
            overdue = overdue < 0 ? 0 : overdue;
            $('#orderEditContent').find('.otherTotal').html(otherTotal.toFixed(2));
            $('#orderEditContent').find('.total').html(total.toFixed(2));
            $('#orderEditContent').find('.receipt').html(receipt.toFixed(2));
            $('#orderEditContent').find('.deposit').html(deposit.toFixed(2));
            $('#orderEditContent').find('.overdue').html(overdue.toFixed(2));
            $('#orderEditContent').find('.order-total').html(parseFloat(total + otherTotal).toFixed(2));             
        }, null);   
    };     
    // 长租房修改订单 -- 金额变化
    var calculateEditLongContentTotal = function(){
        var total = 0;
        var privilege = 0;
        var reducePrice = 0;
        var otherTotal = 0;
        var deposit = 0;
        var otherPrice = 0;
        var otherReceivePrice = parseFloat(window.orderDetailInfo.otherReceivePrice);
        var otherUncollectePrice = parseFloat(window.orderDetailInfo.otherUncollectePrice);
        otherTotal = parseFloat(otherReceivePrice+otherUncollectePrice);
        var receipt = parseFloat(window.orderDetailInfo.receipt);
        var charityprice = window.orderDetailInfo.charityprice;
        $('#editOrderRoom .addOrderLongPrice').each(function(){       
            var isDisabled = $(this).prop("disabled");
            if(!isDisabled){
                total += parseFloat($(this).val());
                reducePrice += parseInt($(this).closest('.addOrderLongTableRoom').find('.months .info').text());
            };
        });
        var receivearr = [];  
        $('#editOrderReceive .addOrderLongReceiveTr').each(function(){
            var isDeposit = $(this).find('.addOrderLongReceiveIsDeposit').data('value');
            var value = parseFloat($(this).find('.addOrderLongReceive').val());
            var type = $(this).find('.addOrderLongReceiveType').data('value');
            var transCurrencyId = $(this).find('.addMultiCurrencyLongType').data('value');
            value = value > 0 ? value : 0;
            var receivePram = {};
            receivePram.isDeposit = isDeposit;
            receivePram.value = value;
            receivePram.type = type;
            receivePram.transCurrencyId = transCurrencyId;
            receivearr.push(receivePram);
        });             
        //汇率转换
        ajaxRequest('/Home/Hotel/getTransCrrencyRate', {
            "hotel": window.currentHotel,
            "transData":receivearr
        }, 'post', function(data) {
            if(data.data.transData){
                $.each(data.data.transData, function (key, value) {
                    var isDeposit = value.isDeposit;
                    var value = parseFloat(value.value);
                    var type = value.type;
                    value = value > 0 ? value : 0;
                    if (isDeposit == 1) {
                        deposit += value;
                    } else if(isDeposit == 0) {
                        receipt += value;
                    } else{
                        if(type !== 0){
                            otherPrice += value;
                        }
                        otherTotal += value;
                    }
                }); 
            };
            if(parseFloat(window.discountrule)>0){ 
                if(parseInt(window.discount) == 0){
                    privilege = parseFloat(total-parseFloat(charityprice))*window.discountrule*100/1000;
                }else{
                    privilege = parseFloat(total)-parseFloat(charityprice)- parseFloat(window.discountrule)*parseInt(reducePrice)+ parseFloat(charityprice);
                } 
                if(privilege<0){
                    privilege = 0;
                }
                $('#orderEditContent').find('.privilege').html(lang('privilege')+window.symbols+ parseFloat(privilege+otherTotal).toFixed(2));
            }else{
                $('#orderEditContent').find('.privilege').html('');
                privilege = total;
            }
            var orderTotal = otherTotal+privilege;
            var overdue = orderTotal - receipt - otherPrice;
            overdue = overdue < 0 ? 0 : overdue;
            $('#orderEditContent').find('.otherTotal').html(otherTotal.toFixed(2));
            $('#orderEditContent').find('.total').html(total.toFixed(2));
            $('#orderEditContent').find('.receipt').html(receipt.toFixed(2));
            $('#orderEditContent').find('.deposit').html(deposit.toFixed(2));
            $('#orderEditContent').find('.overdue').html(overdue.toFixed(2));
            $('#orderEditContent').find('.order-total').html(parseFloat(total + otherTotal).toFixed(2));       
        }, null);           
    };       
    // 收款或者押金变化
    $('#orderEditContent').on('blur', '.addOrderPrice', function(){
        calculateEditContentTotal();
    });    
    $('#orderEditContent').on('blur', '.addOrderReceive', function(){
        calculateEditContentTotal();
    });     
    // 钟点房收款或者押金变化
    $('#orderEditContent').on('blur', '.addOrderHourPrice', function(){
        calculateEditHourContentTotal();
    });    
    $('#orderEditContent').on('blur', '.addOrderHourReceive', function(){
        calculateEditHourContentTotal();
    });       
    // 长租收款或者押金变化
    $('#orderEditContent').on('blur', '.addOrderLongPrice', function(){
        calculateEditLongContentTotal();
    });    
    $('#orderEditContent').on('blur', '.addOrderLongReceive', function(){
        calculateEditLongContentTotal();
    });          
    
    
    // 修改订单 -- 添加入住
    $('#editOrderRoomAdd').on('click', function(e) {
        e.preventDefault();
        var editOrderRooms = $('#editOrderRoom');
        if(window.edithour){
            var selectedDateFormat = editOrderRooms.find('table:first-child .editOrderHourRoomCheckIn').data('time');
            editOrderRooms.append(createEditOrderHourRoomTemplate(selectedDateFormat));
            calculateEditHourContentTotal();
        }else if(window.editlong){
            var selectedDateFormat = editOrderRooms.find('table:first-child .editOrderLongRoomCheckIn').data('value');
            editOrderRooms.append(createEditOrderLongRoomTemplate(selectedDateFormat));
            calculateEditLongContentTotal();
        }else{
            var selectedDateFormat = editOrderRooms.find('table:first-child .editOrderRoomCheckIn').data('value');
            var selectedTime = (new Date(selectedDateFormat)).getTime();
            var sectionStartTime = (new Date(window.startDate)).getTime();
            var sectionEndTime = sectionStartTime + 30 * 86400000;
            if( selectedTime < sectionStartTime || selectedTime > sectionEndTime ){
                formInlineTip($('#editOrderConfirm'), lang('date.scope'));
            	return false;
            }else{
                formInlineTip($('#editOrderConfirm'), '');
            }
            editOrderRooms.append(createEditOrderRoomTemplate(selectedDateFormat));
            calculateEditContentTotal();
        }
    });
    // 修改订单 -- 添加收款
    $('#editOrderReceiveAdd').on('click', function(e) {
        e.preventDefault();
        if(window.edithour){
            $('#editOrderReceive').append(createEditOrderHourReceiveTemplate());
            calculateEditHourContentTotal();
        }else if(window.editlong){
            $('#editOrderReceive').append(createEditOrderLongReceiveTemplate());
            calculateEditLongContentTotal();
        }else{
            $('#editOrderReceive').append(createEditOrderReceiveTemplate());
            calculateEditContentTotal();
        }
    });
    // 去除入住
    $('#orderEditContent').on('click', '.priceRemove', function(e) {
        e.preventDefault();
        var table = $(this).parents('table');
        var addOrderUserRow = table.next('div.row');
        addOrderUserRow.remove();
        table.remove();
        if(window.edithour){
            calculateEditHourContentTotal()         ;   
        }else if(window.editlong){
            calculateEditLongContentTotal();
        }else{
            calculateEditContentTotal();           
        }
    }).on('click', '.receiveRemove', function(e) {
        e.preventDefault();
        var tr = $(this).parents('tr');
        tr.remove();
        if(window.edithour){
            calculateEditHourContentTotal()         ;   
        }else if(window.editlong){
            calculateEditLongContentTotal();
        }else{
            calculateEditContentTotal();           
        }
    }).on('click', '.addUser', function (e) {
        e.preventDefault();
        var me = $(this);
        if(window.edithour){
            var userTemplate = $($('#templateEditOrderHourUser').clone().html());
            var table = me.parents('div.row').prev('table.table.addOrderHourTable.addOrderHourTableRoom');
            userTemplate.attr('data-orderuser', 0);
            table.find('tbody').append(userTemplate);              
        }else if(window.editlong){
            var userTemplate = $($('#templateEditOrderLongUser').clone().html());
            var table = me.parents('div.row').prev('table.table.addOrderLongTable.addOrderLongTableRoom');
            userTemplate.attr('data-orderuser', 0);
            table.find('tbody').append(userTemplate); 
        }else{
            var userTemplate = $($('#templateEditOrderUser').clone().html());
            var table = me.parents('div.row').prev('table.table.addOrderTable.addOrderTableRoom');
            userTemplate.attr('data-orderuser', 0);
            table.find('tbody').append(userTemplate);            
        }

    }).on('click', '.userRemove', function (e) {
        e.preventDefault();     
        var parent = $(this).parents('tr.addOrderUserTr');
        if (parseInt(parent.data('orderuser')) === 0) {
            parent.remove();
        } else {
            parent.addClass('justRemoved').addClass('removed');
            parent.find('.orderUserName').attr('disabled', 1);
            parent.find('.orderUserMobile').attr('disabled', 1);
            parent.find('.orderUserID').attr('disabled', 1);
            parent.find('.userRemove').addClass('hidden');
        }  
        // 停止传递到 .addOrderUserTr 被点击点亮的事件
        e.stopPropagation();
    }).on('click', '.userHourRemove', function (e) {
        e.preventDefault(); 
        var parent = $(this).parents('tr.addOrderHourUserTr');
        if (parseInt(parent.data('orderuser')) === 0) {
            parent.remove();
        } else {
            parent.addClass('justRemoved').addClass('removed');
            parent.find('.orderHourUserName').attr('disabled', 1);
            parent.find('.orderHourUserMobile').attr('disabled', 1);
            parent.find('.orderHourUserID').attr('disabled', 1);
            parent.find('.userHourRemove').addClass('hidden');
        }  
        // 停止传递到 .addOrderUserTr 被点击点亮的事件
        e.stopPropagation();
    }).on('click', '.userLongRemove', function (e) {
        e.preventDefault(); 
        var parent = $(this).parents('tr.addOrderLongUserTr');
        if (parseInt(parent.data('orderuser')) === 0) {
            parent.remove();
        } else {
            parent.addClass('justRemoved').addClass('removed');
            parent.find('.orderLongUserName').attr('disabled', 1);
            parent.find('.orderLongUserMobile').attr('disabled', 1);
            parent.find('.orderLongUserID').attr('disabled', 1);
            parent.find('.userLongRemove').addClass('hidden');
        }  
        // 停止传递到 .addOrderUserTr 被点击点亮的事件
        e.stopPropagation();
    }).on('click', '.addOrderUserTr', function (e) {
        // 点击重新点亮
        e.preventDefault();
        var me = $(this);
        if (!me.hasClass('justRemoved')) {
            return false;
        }
        me.removeClass('removed').removeClass('justRemoved');
        me.find('.userRemove').removeClass('hidden');
        me.find('.orderUserName').removeAttr('disabled');
        me.find('.orderUserMobile').removeAttr('disabled');
        me.find('.orderUserID').removeAttr('disabled');
    });

    // 办理退房触发按钮
    $('#initCheckOut').on('click', function(e) {
        var initContent = $('#orderInitContent');
        var orderValue = initContent.data('parent');
        var orderRoomValue = initContent.data('value');
        var confirmBtn = $('#editOrderConfirm');
        confirmBtn.data('parent', orderValue);
        confirmBtn.data('value', orderRoomValue);
        var checkoutContent = $('#orderCheckOutContent');
        var orderDetail = window.orderDetailInfo;
        // 请求订单收款以及押金记录
        var param = {};
        param.hotel = window.currentHotel;
        param.order = orderValue;
        ajaxRequest('/Home/Order/getPayHistory', param, 'post', function(data) {
            var payRecord = $('#checkoutPayRecord');
            if (data.data.length === 0) {
                $('#checkoutPayEmpty').removeClass('hidden');
                $('#checkoutPayContainer').addClass('hidden');
                $('#checkoutRefoundDeposit').addClass('hidden');
            } else {
                $('#checkoutRefoundDeposit').removeClass('hidden');
                $('#checkoutPayContainer').removeClass('hidden');
                $('#checkoutPayEmpty').addClass('hidden');
                var records = '';
                $.each(data.data, function(index, record) {
                    var template;
                    if (record.type === '0') {
                        template = $($('#templateOrderPayRecordReceipt').clone().html());
                    } else if(record.type === '1') {
                        template = $($('#templateOrderPayRecordDeposit').clone().html());
                    }else{
                        template = $($('#templateOrderPayRecordOther').clone().html());
                        template.find('.source').html(record.otherCostName);
                    }
                    template.find('.paytype').html(record.name);
                    template.find('.info').html(record.pay);
                    records += template.prop('outerHTML');
                });
                payRecord.html(records);
            }
        }, null);
        var refundInfo = orderDetail.payHistory.refundInfo;
        var refundRecord = $('#checkoutRetreatRecord');
        if (refundInfo.length === 0) {
            $('#checkoutRetreatRecord').addClass('hidden');
            $('#checkoutRetreatRecord').prev(".vertical-margin").addClass('hidden');
        } else {
            $('#checkoutRetreatRecord').removeClass('hidden');
            $('#checkoutRetreatRecord').prev(".vertical-margin").removeClass('hidden');
            var records = '';
            $.each(refundInfo, function(index, record) {
                var template;
                if (record.type === '2') {
                    template = $($('#templateOrderRefundRecordReceipt').clone().html());
                } else {
                    template = $($('#templateOrderRefundRecordDeposit').clone().html());
                }
                template.find('.paytype').html(record.name);
                template.find('.info').html(record.pay);
                records += template.prop('outerHTML');
            });
            refundRecord.html(records);
        }
        
        // 加入可退房的房间选项
        var templateOriginal = $('#templateCheckoutOrderRoom');
        var checkoutRooms = $('#checkoutRooms');
        var orderRooms = '';
        var checkoutableRooms = 0;
        $.each(orderDetail.rooms, function(index, orderRoomInfo) {
            // 当订单状态是已入住的情况下，可退房
            if (orderRoomInfo.status === window.orderStatus.checkin || orderRoomInfo.status === window.orderStatus.needOut) {
                var template = $(templateOriginal.clone().html());
                template.find('.checkbox').attr('data-value', orderRoomInfo.id);
                var userNames = [];
                for (var index in orderRoomInfo.user) {
                    if (parseInt(orderRoomInfo.user[index].isdelete) === 1) {
                        continue;
                    }
                    userNames.push(orderRoomInfo.user[index].name);
                }
                userNames = userNames.join(',');
                template.find('.username').html(userNames);

                // 计算实住
                var templateEnd = getDate(orderRoomInfo.enddate);
                var nightToEnd = today.getDays(templateEnd);
                if (nightToEnd < 0) {
                    var night = today.getDays(getDate(orderRoomInfo.startdate));
                } else {
                    var night = templateEnd.getDays(getDate(orderRoomInfo.startdate));
                }

                // 有设置下单时间的订单 计算实住 
                if (orderRoomInfo.ismidnightorder) {
                    night++;
                }

                template.find('.room').html(orderRoomInfo.room);
                template.find('.type').html(orderRoomInfo.type);
                template.find('.pay').html(orderRoomInfo.pay);
                if(orderRoomInfo.hour > 0){
                    template.find('.checkoutOrderHour').removeClass('hidden');
                    template.find('.checkoutOrderNight').addClass('hidden');
                    template.find('.checkoutOrderLong').addClass('hidden');
                    template.find('.checkoutOrderHour .startdate').html(orderRoomInfo.starttime);  
                    template.find('.hour').html(orderRoomInfo.hour < 0 ? 0 : orderRoomInfo.hour);   
                }else if(orderRoomInfo.month > 0){
                    template.find('.checkoutOrderLong').removeClass('hidden');
                    template.find('.checkoutOrderHour').addClass('hidden');
                    template.find('.checkoutOrderNight').addClass('hidden');
                    template.find('.checkoutOrderNight .startdate').html(getDate(orderRoomInfo.startdate).customFormat(lang('tip.date')));
                    template.find('.enddate').html(getDate(orderRoomInfo.enddate).customFormat(lang('tip.date')));  
                    template.find('.long').html(orderRoomInfo.night < 0 ? 0 : orderRoomInfo.night);     
                }else{
                    template.find('.checkoutOrderNight').removeClass('hidden');
                    template.find('.checkoutOrderHour').addClass('hidden');
                    template.find('.checkoutOrderLong').addClass('hidden');
                    template.find('.checkoutOrderNight .startdate').html(getDate(orderRoomInfo.startdate).customFormat(lang('tip.date')));
                    template.find('.enddate').html(getDate(orderRoomInfo.enddate).customFormat(lang('tip.date')));  
                    template.find('.night').html(night < 0 ? 0 : night);                   
                }
                orderRooms += template.prop('outerHTML');
                checkoutableRooms++;
            }
        });
        checkoutRooms.html(orderRooms);
        var selectedRoomInput = checkoutRooms.find('.checkbox[data-value="' + orderRoomValue + '"]').find('input');
        selectedRoomInput.prop('checked', true);
        if (checkoutableRooms === 1) {
            selectedRoomInput.attr('disabled', true);
        }
        componentHandler.upgradeAllRegistered();
        // 总费用，已收款，待付款
        checkoutContent.find('.total').html(orderDetail.pay);
        checkoutContent.find('.deposit').html(orderDetail.deposit);
        checkoutContent.find('.receipt').html(orderDetail.receipt);
        checkoutContent.find('.receipt-refund').html(orderDetail.refundPrice == '' ? '0.00' : orderDetail.refundPrice.toFixed(2));
        checkoutContent.find('.deposit-refund').html(orderDetail.refundDeposit== '' ? '0.00' : orderDetail.refundDeposit.toFixed(2));
        var depositPrice = 0;
        if(orderDetail.refundDeposit){
            depositPrice = parseFloat(orderDetail.refundDeposit);
        }
        checkoutContent.find('.retreat-deposit').html(parseFloat(parseFloat(orderDetail.deposit) - depositPrice).toFixed(2));
        var refundPrice = 0;
        if(orderDetail.refundPrice){
            refundPrice = parseFloat(orderDetail.refundPrice);
        }
        var retreatMoney = parseFloat(parseFloat(orderDetail.receipt)- refundPrice - parseFloat(orderDetail.pay)).toFixed(2);
        if(retreatMoney>0){
            checkoutContent.find('.retreat').html(retreatMoney);
            checkoutContent.find('.retreat-list').text(lang('retreat.1'));
        }else{
            checkoutContent.find('.retreat-list').text(lang('retreat.2'));
            checkoutContent.find('.retreat').html(parseFloat(parseFloat(orderDetail.pay) - parseFloat(orderDetail.receipt) + refundPrice).toFixed(2));
        }
        // 重置收款 重置提交按钮状态
        $('#checkOutReceipt').val('');
        $('#checkOutDeposit').val('');
        formInlineRight($('#checkoutConfirm'));
        // 备注
        $('#checkOutRemark').val(orderDetail.remark);
        initContent.addClass('hidden');
        checkoutContent.removeClass('hidden');
    });
    // 办理退房自动校验
    $('#checkOutForm').inputValidate({
        submit: {
            query: '#checkoutConfirm'
        },
        inputs: [{
            query: '#checkOutReceipt',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.money')
        }, {
            query: '#checkOutDeposit',
            regexp: window.commonRegexp.roomTypePrice,
            required: false,
            message: lang('tip.cash')
        }, {
            query: '#checkOutRemark',
            regexp: window.commonRegexp.nameLength255,
            required: false,
            message: lang('tip.remark')
        }]
    });
    $('#checkoutConfirm').on('successSubmit.amos.inputValidate', function(e) {
        var $me = $(this),
            receipt = $('#checkOutReceipt').val().trim(),
            deposit = $('#checkOutDeposit').val().trim(),
            remark = $('#checkOutRemark').val().trim(),
            param = {
                suborder: []
            },
            initContent = $('#orderInitContent'),
            operating = initContent.data('parent');
        // operatingSub = initContent.data('value');
        $('#checkoutRooms .checkbox').each(function() {
            if ($(this).find('input[type=checkbox]').get(0).checked === true) {
                param.suborder.push($(this).attr('data-value'));
            }
        });
        param.suborder = param.suborder.join(',');
        if (param.suborder == '') {
            formInlineTip($me, lang('checkOrder'));
            return false;
        }
        if (receipt != '') {
            if ($('#checkOutReceiptType').data('value') == 1 && receipt != 0) {
                receipt = '-' + receipt;
            }
            param.receipt = receipt;
            param.receiptpay = $('#checkOutReceiptPay').data('value');
            param.receiptCurrencyId = $('#checkOutReceiptCurrencyType').data('value');
        }
        if (deposit != '') {
            param.deposit = deposit === 0 ? 0 : '-' + deposit;
            param.depositpay = $('#checkOutDepositPay').data('value');
            param.depositCurrencyId = $('#checkOutDepositCurrencyType').data('value');
        }
        param.remark = remark;
        param.hotel = window.currentHotel;
        param.order = operating;
        if(window.checkroom){
            $('#whetherCheckRoomModal').show().find('.unconfirmCheckRoom').attr({'data-order':param.order,'data-suborder':param.suborder});
        }else{
            ajaxRequest('/Home/Order/checkout', param, 'post', null, null, $me);
        }
    });
    //查房模态框
    $('#whetherCheckRoomModal').on('click','.close',function(e){
        e.stopPropagation();
        $('#whetherCheckRoomModal').hide();
    }).on('click','.unconfirmCheckRoom',function(e){
        e.stopPropagation();
        var order = $(this).attr('data-order');
        var suborder = $(this).attr('data-suborder');
        showMainLoading();
        ajaxRequest('/Home/Order/orderRoomCheck', {
            "hotel": window.currentHotel,
            "order":order,
            "suborder":suborder
        }, 'post', function(data) {
            hideMainLoading();
            $('#whetherCheckRoomModal').hide();
            $('#affirmCheckRoomModal').show();            
        }, function(error) { 
            hideMainLoading();
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });         
    }).on('click','.confirmCheckRoom',function(e){
        e.stopPropagation();
        $('#whetherCheckRoomModal').hide();
        window.checkroom = false;
    });
    $('#affirmCheckRoomModal').on('click','.close',function(e){
        e.stopPropagation();
        $('#affirmCheckRoomModal').hide();
    }).on('click','.confirmCloseRoom',function(e){
        e.stopPropagation();
        $('#orderDetailModal').modal('hide');
        $('#affirmCheckRoomModal').hide();
    }).on('click','.confirmCheckOutRoom',function(e){
        e.stopPropagation();
        $('#affirmCheckRoomModal').hide();
        window.checkroom = false;
    });
    // 修改订单 -- 产生房间模板
    var createEditOrderRoomTemplate = function(selectedDateFormat, orderRoomInfo, removeAble, editable) {
        removeAble = removeAble === undefined ? true : removeAble;
        editable = editable === undefined ? true : editable;
        var template = $($('#templateEditOrderRoom').clone().html());
        // 添加可选日期，选择日期
        var dateList = '';
        var selectedDate = getDate(selectedDateFormat);
        var startDateObj = getDate(window.startDate);
        var beforeStartDays = selectedDate.getDays(startDateObj);
        var startRenderCount = beforeStartDays > 0 ? 0 : beforeStartDays;
        var renderCount = 31;
        var changeDate;
        for (var i = startRenderCount; i < renderCount; i++) {
            changeDate = startDateObj.customDays(i).customFormat();
            if (i === beforeStartDays) {
                dateList += '<li data-value="' + changeDate + '" class="active"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            } else {
                dateList += '<li data-value="' + changeDate + '"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            }
        }
        template.find('.editOrderRoomCheckInMenu').html(dateList);
        template.find('.editOrderRoomCheckIn').attr('data-value', selectedDateFormat);
        template.find('.editOrderRoomCheckIn .info').html(selectedDateFormat);
        // 选择房间
        var selectedRoomLi, selectedRoomValue, selectedRoomName;
        if (orderRoomInfo !== undefined) {
            selectedRoomLi = template.find('.editOrderRoomIdMenu li[data-value="' + orderRoomInfo.roomid + '"]');
            selectedRoomValue = orderRoomInfo.roomid;
            selectedRoomName = orderRoomInfo.room;
            // 选择晚数，填充价格，入住人信息
            var selectedDateLi = template.find('.editOrderRoomNightMenu li[data-value="' + orderRoomInfo.night + '"]');
            if(orderRoomInfo.status == window.orderStatus.checkout || orderRoomInfo.status == window.orderStatus.cancelled){
                template.find('.realLive').html(lang('live'));
            }else{
                template.find('.realLive').html('');
            }            
            template.find('.editOrderRoomNight').attr('data-value', selectedDateLi.data('value'));
            template.find('.editOrderRoomNight .info').html(selectedDateLi.find('a').html());
            template.find('.addOrderPrice').attr('value', orderRoomInfo.pay);
            for (var j = 0; j < orderRoomInfo.user.length; j++) {
                var orderUserTemplate = $($('#templateEditOrderUser').clone().html());
                orderUserTemplate.find('.orderUserName').attr('value', orderRoomInfo.user[j].name);
                orderUserTemplate.find('.areaCodeValue').text(orderRoomInfo.user[j].areaCode);
                orderUserTemplate.find('.orderUserMobile').attr('value',orderRoomInfo.user[j].mobile);
                orderUserTemplate.find('.orderUserID').attr('value', orderRoomInfo.user[j].identity);
                orderUserTemplate.attr('data-orderuser', orderRoomInfo.user[j].orderUser);
                // 已删除的同住人不能再删除
                if (parseInt(orderRoomInfo.user[j].isdelete) === 1) {
                    orderUserTemplate.addClass('removed').find('.userRemove').addClass('hidden');
                }
                template.find('tbody').append(orderUserTemplate);
            }
            template.attr('data-value', orderRoomInfo.id);
        } else {
            selectedRoomLi = template.find('.editOrderRoomIdMenu li:first-child');
            template.find('.addOrderPrice').attr('value', calculateRoomPrice(selectedDateFormat,selectedRoomLi.data('value'),1));
            var orderUserTemplate = $($('#templateEditOrderUser').clone().html());
            orderUserTemplate.attr('data-orderuser', 0);
            template.find('tbody').append(orderUserTemplate);
            selectedRoomValue = selectedRoomLi.data('value');
            selectedRoomName = selectedRoomLi.find('a').html();
        }
        selectedRoomLi.addClass('active');
        template.find('.editOrderRoomId').attr('data-value', selectedRoomValue);
        template.find('.editOrderRoomId .info').html(selectedRoomName);
        if (!removeAble) {
            template.find('.priceRemove').addClass('hidden');
        }
        if (!editable) {
            template.find('.orderUserName').prop('disabled', true);
            template.find('.orderUserMobile').prop('disabled', true);
            template.find('.orderUserID').prop('disabled', true);
            template.find('.addOrderPrice').prop('disabled', true);
            template.find('.editOrderRoomCheckIn').addClass('disabled');
            template.find('.editOrderRoomId').addClass('disabled');
            template.find('.editOrderRoomNight').addClass('disabled');

            return template.prop('outerHTML');
        } else {
            return template.prop('outerHTML') + '<div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addUser text-primary">'+lang('addCohabit')+'</div></div></div>';
        }
    };
    // 钟点房修改订单 -- 产生房间模板
    var createEditOrderHourRoomTemplate = function(selectedDateFormat, orderRoomInfo, removeAble, editable) {
        removeAble = removeAble === undefined ? true : removeAble;
        editable = editable === undefined ? true : editable;
        var template = $($('#templateHourEditOrderRoom').clone().html());
        // 添加可选日期，选择日期
        var dateHourList = '';
        var dateminuteList = '';
        var getHours = parseInt(new Date().getHours());
        var getMinutes = parseInt(new Date().getMinutes());
        if(getMinutes<10){
           getMinutes = '0'+getMinutes 
        }
        window.presenttime = getHours+':'+getMinutes;
        template.find('#_contents .dropdown_hour .info').html(getHours);
        for(var i = 0; i < 24; i++) {
            if(i < 10) {
                i = '0' + i;
            } 
            dateHourList += '<li data-value="' + i + '"><a href="javascript:void(0);">' + i + '</a></li>';
        }
        template.find('#_contents .dropdown_hour ul').html(dateHourList);
        for(var j = 0; j <= 59; j++) {
            if(j < 10) {
                j = '0' + j;
            } 
            dateminuteList += '<li data-value="' + j + '"><a href="javascript:void(0);">' + j + '</a></li>';
        }
        template.find('#_contents .dropdown_minute ul').html(dateminuteList); 
        // 选择房间
        var selectedRoomLi, selectedRoomValue, selectedRoomName;
        if (orderRoomInfo !== undefined) {
            selectedRoomLi = template.find('.editOrderHourRoomIdMenu li[data-value="' + orderRoomInfo.roomid + '"]');
            selectedRoomValue = orderRoomInfo.roomid;
            selectedRoomName = orderRoomInfo.room;
            var dateHour = orderRoomInfo.starttime.substr(11,5);
            template.find('.editOrderHourRoomCheckIn').data('value',dateHour).find('.info').html(dateHour);
            // 选择晚数，填充价格，入住人信息
            var selectedDateLi = template.find('.addOrderRoomHourMenu li[data-value="' + orderRoomInfo.hour + '"]');
            if(orderRoomInfo.status == window.orderStatus.checkout || orderRoomInfo.status == window.orderStatus.cancelled){
                template.find('.realLive').html(lang('live'));
            }else{
                template.find('.realLive').html('');
            }            
            template.find('.editOrderHourRoomCheckIn').attr('data-time', selectedDateFormat);
            template.find('.addOrderHourRoom').attr('data-value', selectedDateLi.data('value'));
            template.find('.addOrderHourRoom .info').html(selectedDateLi.find('a').html());
            template.find('.addOrderHourPrice').attr('value', orderRoomInfo.pay);
            for (var j = 0; j < orderRoomInfo.user.length; j++) {
                var orderUserTemplate = $($('#templateEditOrderHourUser').clone().html());
                orderUserTemplate.find('.orderHourUserName').attr('value', orderRoomInfo.user[j].name);
                orderUserTemplate.find('.orderHourUserMobile').attr('value', orderRoomInfo.user[j].mobile);
                orderUserTemplate.find('.orderHourUserID').attr('value', orderRoomInfo.user[j].identity);
                orderUserTemplate.attr('data-orderuser', orderRoomInfo.user[j].orderUser);
                // 已删除的同住人不能再删除
                if (parseInt(orderRoomInfo.user[j].isdelete) === 1) {
                    orderUserTemplate.addClass('removed').find('.userRemove').addClass('hidden');
                }
                template.find('tbody').append(orderUserTemplate);
            }
            template.attr('data-value', orderRoomInfo.id);
        } else {
            selectedRoomLi = template.find('.editOrderHourRoomIdMenu li:first-child');
            template.find('.editOrderHourRoomCheckIn').attr('data-time', selectedDateFormat);
            template.find('.addOrderHourPrice').attr('value', calculateHourRoomPrice(selectedDateFormat,selectedRoomLi.data('value'),2));
            var orderUserTemplate = $($('#templateEditOrderHourUser').clone().html());
            orderUserTemplate.attr('data-orderuser', 0);
            template.find('.editOrderHourRoomCheckIn').data('value',window.enteringtime).find('.info').html(window.presenttime);
            template.find('tbody').append(orderUserTemplate);
            selectedRoomValue = selectedRoomLi.data('value');
            selectedRoomName = selectedRoomLi.find('a').html();
        }
        selectedRoomLi.addClass('active');
        template.find('.editOrderHourRoomId').attr('data-value', selectedRoomValue);
        template.find('.editOrderHourRoomId .info').html(selectedRoomName);
        if (!removeAble) {
            template.find('.priceRemove').addClass('hidden');
        }
        if (!editable) {
            template.find('.orderHourUserName').prop('disabled', true);
            template.find('.orderHourUserMobile').prop('disabled', true);
            template.find('.orderHourUserID').prop('disabled', true);
            template.find('.addOrderHourPrice').prop('disabled', true);
            template.find('.editOrderHourRoomCheckIn').addClass('disabled');
            template.find('.editOrderHourRoomId').addClass('disabled');
            template.find('.addOrderHourRoom').addClass('disabled');

            return template.prop('outerHTML');
        } else {
            return template.prop('outerHTML') + '<div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addUser text-primary">'+lang('addCohabit')+'</div></div></div>';
        }
    };    
    // 长租房修改订单 -- 产生房间模板
    var createEditOrderLongRoomTemplate = function(selectedDateFormat, orderRoomInfo, removeAble, editable) {
        removeAble = removeAble === undefined ? true : removeAble;
        editable = editable === undefined ? true : editable;
        var template = $($('#templateLongEditOrderRoom').clone().html());
        // 添加可选日期，选择日期
        var dateLongList = '';
        var selectedDate = getDate(selectedDateFormat);
        var startDateObj = getDate(window.startDate);
        var beforeStartDays = selectedDate.getDays(startDateObj);
        var startRenderCount = beforeStartDays > 0 ? 0 : beforeStartDays;
        var renderCount = 31;
        var changeDate;
        for (var i = startRenderCount; i < renderCount; i++) {
            changeDate = startDateObj.customDays(i).customFormat();
            if (i === beforeStartDays) {
                dateLongList += '<li data-value="' + changeDate + '" class="active"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            } else {
                dateLongList += '<li data-value="' + changeDate + '"><a href="javascript:void(0);">' + changeDate + '</a></li>';
            }
        }
        template.find('.editOrderLongRoomCheckInMenu').html(dateLongList);
        template.find('.editOrderLongRoomCheckIn').attr('data-value', selectedDateFormat);
        template.find('.editOrderLongRoomCheckIn .info').html(selectedDateFormat);
        // 选择房间
        var selectedRoomLi, selectedRoomValue, selectedRoomName;
        if (orderRoomInfo !== undefined) {
            selectedRoomLi = template.find('.editOrderLongRoomIdMenu li[data-value="' + orderRoomInfo.roomid + '"]');
            selectedRoomValue = orderRoomInfo.roomid;
            selectedRoomName = orderRoomInfo.room;
            // 选择晚数，填充价格，入住人信息
            var selectedDateLi = template.find('.addOrderRoomLongMenu li[data-value="' + orderRoomInfo.month + '"]');
            if(orderRoomInfo.status == window.orderStatus.checkout || orderRoomInfo.status == window.orderStatus.cancelled){
                template.find('.realLive').html(lang('live'));
            }else{
                template.find('.realLive').html('');
            }            
            template.find('.editOrderLongRoomCheckIn').attr('data-value', selectedDateFormat);
            template.find('.addOrderRoomLong').attr('data-value', selectedDateLi.data('value'));
            template.find('.addOrderRoomLong .info').html(selectedDateLi.find('a').html());
            template.find('.addOrderLongPrice').attr('value', orderRoomInfo.pay);
            
            for (var j = 0; j < orderRoomInfo.user.length; j++) {
                var orderUserTemplate = $($('#templateEditOrderLongUser').clone().html());
                orderUserTemplate.find('.orderLongUserName').attr('value', orderRoomInfo.user[j].name);
                orderUserTemplate.find('.orderLongUserMobile').attr('value', orderRoomInfo.user[j].mobile);
                orderUserTemplate.find('.orderLongUserID').attr('value', orderRoomInfo.user[j].identity);
                orderUserTemplate.attr('data-orderuser', orderRoomInfo.user[j].orderUser);
                // 已删除的同住人不能再删除
                if (parseInt(orderRoomInfo.user[j].isdelete) === 1) {
                    orderUserTemplate.addClass('removed').find('.userRemove').addClass('hidden');
                }
                template.find('tbody').append(orderUserTemplate);
            }
            template.attr('data-value', orderRoomInfo.id);
        } else {
            selectedRoomLi = template.find('.editOrderLongRoomIdMenu li:first-child');
            template.find('.editOrderLongRoomCheckIn').attr('data-value', selectedDateFormat);
            template.find('.addOrderLongPrice').attr('value', calculateLongRoomPrice(selectedDateFormat,selectedRoomLi.data('value'),1));
            var orderUserTemplate = $($('#templateEditOrderLongUser').clone().html());
            orderUserTemplate.attr('data-orderuser', 0);
            template.find('tbody').append(orderUserTemplate);
            selectedRoomValue = selectedRoomLi.data('value');
            selectedRoomName = selectedRoomLi.find('a').html();   
        }
        selectedRoomLi.addClass('active');
        template.find('.editOrderLongRoomId').attr('data-value', selectedRoomValue);
        template.find('.editOrderLongRoomId .info').html(selectedRoomName);
        if (!removeAble) {
            template.find('.priceRemove').addClass('hidden');
        }
        if (!editable) {
            template.find('.orderLongUserName').prop('disabled', true);
            template.find('.orderLongUserMobile').prop('disabled', true);
            template.find('.orderLongUserID').prop('disabled', true);
            template.find('.addOrderLongPrice').prop('disabled', true);
            template.find('.editOrderLongRoomCheckIn').addClass('disabled');
            template.find('.editOrderLongRoomId').addClass('disabled');
            template.find('.addOrderLongRoom').addClass('disabled');

            return template.prop('outerHTML');
        } else {
            return template.prop('outerHTML') + '<div class="row"><div class="col-xs-12"><div class="btn-sm btn-link btn-success addUser text-primary">'+lang('addCohabit')+'</div></div></div>';
        }
    };      
    //时间
    $('#orderEditContent').on('click','.editOrderHourRoomCheckIn',function(e){
        e.stopPropagation();
        e.preventDefault();
        timeSelectContainer = $(this).closest('.time-select-container').find('.time-container');
        if(timeSelectContainer.hasClass('hidden')){
            timeSelectContainer.removeClass('hidden');
        }else{
            timeSelectContainer.addClass('hidden');
        }
    }).on('click','.clear_time',function(e){
        e.stopPropagation();
        e.preventDefault();
        _contents = $(this).closest('#_contents');
        _contents.closest('.time-container').addClass('hidden');
    }).on('click','.select_time',function(e){
        e.stopPropagation();
        e.preventDefault();
        _contents = $(this).closest('#_contents');
        var hour = _contents.find('.dropdown_hour .info').text();
        var minute = _contents.find('.dropdown_minute .info').text();
        if(hour!=''&&minute!=''){
            _contents.closest('.time-select-container').find('.editOrderHourRoomCheckIn .info').text(hour+':'+minute);
        }
        _contents.closest('.time-container').addClass('hidden');
    });
    // 修改订单 -- 产生收款模板
    var createEditOrderReceiveTemplate = function() {
        var template = $($('#templateEditOrderReceive').clone().html());
        return template.prop('outerHTML');
    };
    // 钟点房修改订单 -- 产生收款模板
    var createEditOrderHourReceiveTemplate = function() {
        var template = $($('#templateEditOrderHourReceive').clone().html());
        return template.prop('outerHTML');
    };    
    // 长租房修改订单 -- 产生收款模板
    var createEditOrderLongReceiveTemplate = function() {
        var template = $($('#templateEditOrderLongReceive').clone().html());
        return template.prop('outerHTML');
    }; 
    // 显示订单操作历史
    $('.orderDetailRecord').on('click', function(e) {
        var initContent = $('#orderInitContent');
        var orderHistoryContent = $('#orderHistoryContent');
        var orderValue = initContent.data('parent');
        var param = {};
        param.hotel = window.currentHotel;
        param.order = orderValue;
        ajaxRequest('/Home/Order/getHistory', param, 'post', function(data) {
            var templateOriginal = $('#templateOrderRecord');
            var templates = '';
            $.each(data.data.change.reverse(), function(index, changeInfo) {
                var templateOrderRecord = $(templateOriginal.clone().html());
                var date = changeInfo.time.substr(0, 10);
                var time = changeInfo.time.substr(-8);
                templateOrderRecord.find('.date').html(date);
                templateOrderRecord.find('.time').html(time);
                templateOrderRecord.find('.from').html(changeInfo.from);
                templateOrderRecord.find('.by').html(changeInfo.by);
                var detailInfo = '';
                if (changeInfo.p !== undefined) {
                    detailInfo += '<p>' + changeInfo.p + '</p>';
                }
                if (changeInfo.i !== undefined) {
                    detailInfo += '<p>' + changeInfo.i + '</p>';
                }
                if (changeInfo.r !== undefined) {
                    detailInfo += '<p>' + changeInfo.r.replace(/\\n/g, '<br />') + '</p>';
                }
                if (changeInfo.u !== undefined) {
                    detailInfo += '<p>' + changeInfo.u.replace(/\\n/g, '<br />') + '</p>';
                }
                if (changeInfo.z !== undefined) {
                    detailInfo += '<p>' + changeInfo.z.replace(/\\n/g, '<br />') + '</p>';
                }
                if (changeInfo.c !== undefined) {
                    detailInfo += '<p>' + changeInfo.c.replace(/\\n/g, '<br />') + '</p>';
                }
                templateOrderRecord.find('.order-record-content').html(detailInfo);
                templates += templateOrderRecord.prop('outerHTML');
            });
            $('#orderRecordContainer').html(templates);

            // 将显示的页面隐藏
            var activeContent = initContent;
            orderHistoryContent.siblings().addClass('hidden');
            orderHistoryContent.removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));
        }, function(error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });
     // 显示订单房卡分享记录
    $('.shareCardRecord').on('click', function(e) {
        var initContent = $('#orderInitContent');
        var shareContent = $('#shareCardContent');
        var orderRoomValue = initContent.data('value');
        var param = {};
        param.hotel = window.currentHotel;
        param.orderRoomId = orderRoomValue;
        ajaxRequest('/Home/Order/getShareHistory', param, 'post', function(data) {
            var templateOriginal = $('#templateShareRecord');
            var templates = '';
            var changeData = data.data;
            if(changeData == ''){
                $('#shareCardContainer').html('<div class="text-center" style="font-size: 14px; padding: 8px 0px;">'+lang("No.qr")+'</div>');
            }else{
                $.each(changeData, function(index, changeInfo) {
                    var templateOrderRecord = $(templateOriginal.clone().html());
                    var date = changeInfo.time.substr(0, 10);
                    var time = changeInfo.time.substr(-8);
                    templateOrderRecord.find('.date').html(date);
                    templateOrderRecord.find('.time').html(time);
                    templateOrderRecord.find('.by').html(changeInfo.by);
                    if(changeInfo.opfrom == 0){
                        templateOrderRecord.find('.from').html(lang('meizhu.app'));
                    }else{
                        templateOrderRecord.find('.from').html(lang('meizhu.webBook'));
                    }
                    var detailInfo = '';
                    if(changeInfo.mobile != ''){
                        detailInfo = '<p>'+lang('share')+changeInfo.roomtype+'-'+changeInfo.roomname+lang('qrTo')+'+'+changeInfo.areacode+' '+changeInfo.mobile+'</p>';
                    }else{
                        detailInfo = '<p>'+lang('share')+changeInfo.roomtype+'-'+changeInfo.roomname+lang('qrTo')+changeInfo.mobile+'</p>';
                    }
                    templateOrderRecord.find('.share-record-content').html(detailInfo);
                    templates += templateOrderRecord.prop('outerHTML');
                });
                $('#shareCardContainer').html(templates);
            }
             // 将显示的页面隐藏
            var activeContent = initContent;
            shareContent.siblings().addClass('hidden');
            shareContent.removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));   
        }, function(error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });
    // 切换显示订单详情
    $('.orderDetailRecordReturn').on('click', function(e) {
        var activeContent = $('#orderHistoryContent');
        var orderInitContent = $('#orderInitContent');
        orderInitContent.siblings().addClass('hidden');
        $('#orderInitContent').removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));
    });  
    // 切换显示签发RF卡  
    $('.orderRfcard').on('click', function(e) {
        var activeContent = $('#orderHistoryContent');
        var orderQRContent = $('#orderQRContent');
        orderQRContent.siblings().addClass('hidden');
        orderQRContent.removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));
    });
    
    //RF卡错误提示
    var isIE = (navigator.userAgent.indexOf('MSIE')>=0) || (navigator.userAgent.indexOf('Trident')>=0);
    var RFCardError = function(errorno){
        var error = '';
        switch(errorno) {
            case 101:
                error = lang('RF.1');
                break;
            case 102:
                error = lang('RF.2');
				modalAlertRF(error);
                break;
            case 103:
                error = lang('RF.3');
                break;
            case 104:
                error = lang('RF.4');
                break;
            case 105:
                error = lang('RF.5');
                break;
            case 106:
                error = lang('RF.6');
                break;
        }
        hideCardLoading();
		if(errorno!=102){
			modalAlert(error);
		}
        return false;
    } 
    //签发RF卡
    $('#orderRfContainer').on('click','.printRfCard',function(){
        writeRfCard($(this),0);
    })    
    //挂失RF卡
    $('#orderRfContainer').on('click','.lostRf',function(e){
        writeRfCard($(this),1);
    });    
    var writeRfCard = function(obj,status){
        var isTypeJiu = $('#objectHTML').attr('isTypeJiu');
        var isTypeSi = $('#objectHTML').attr('isTypeSi');
        var params = {
            hotel: window.currentHotel,
            order: window.orderDetailInfo.id,
            userRoom: obj.data('userRoom'),
            subOrder: obj.data('value'),
            lost : status,
        };        
        ajaxRequest('/Home/Order/getRFData', params, 'post', function(data) {            
            var info = data.data;
            var whichType = info.lockType;
            if(!info.isClientAvailable){
                if(!isIE){
                    RFCardError(101);
                }else{
                    showCardLoading();
                    if(whichType == '2'){
                        if(isTypeJiu != 'true') {
                            var objectHTML = '<OBJECT id="IEV957M1CLS" classid="clsid:FAA6C3FA-CBB7-48B8-8269-016E259C4E2B"></OBJECT>';
                            $('#objectHTML').append(objectHTML).attr('isTypeJiu', true);
                        }
                        var openStatus = OpenUSB57M1();
                        if(openStatus == undefined) {
                            //插件未安装
                            CloseUSB57M1();
                            RFCardError(102);
                            return;
                        }
                        if(openStatus != 0){
                            //发卡器未连接
                            CloseUSB57M1();
                            RFCardError(103);
                            return;
                        }
                        var oldCardData = ReadCard57M1();
                        if(oldCardData == ''){
                            //无法识别感应卡
                            CloseUSB57M1();
                            RFCardError(104);
                            return;
                        }
                        if(guest57M1(info.cardData) != 0) {
                            //无法识别感应卡
                            CloseUSB57M1();
                            RFCardError(104);
                            return;
                        }
                        var RetData = ReadCard57M1();
                        Buzzer57M1(20);
                        CloseUSB57M1();
                        ajaxRequest('/Home/Order/reportRFData',{
                            "hotel" : window.currentHotel,
                            "serialNum": info.serialNum,
                            "cardData": RetData,
                            "userRoom":obj.data('userRoom'),
                            "oldCardData":oldCardData,
                        }, 'post', function(data){
                            var row = obj.closest('.row');
                            var printCount = parseInt(row.find('.printCount').text());
                            if(printCount <= 0){
                                row.find('.lostRf').removeClass('text-disable');
                            }
                            printCount++;
                            row.find('.printCount').text(printCount);
                            if(status == 0){
                                layer.msg(lang('RF.8'), {icon: 1});
                            }else{
                                layer.msg(lang('RF.9'), {icon: 1});
                            }
                        }, null);               
                    }else if(whichType == '3'){
                        if(isTypeSi != 'true'){
                          var objectHTML = '<OBJECT id=IEQRM1CLS classid="clsid:E7A609EB-0AE9-46C6-BB9C-5D8ECE503D7C"></OBJECT>';
                          $('#objectHTML').append(objectHTML).attr('isTypeSi',true);
                        }
                        var openStatus = OpenUSBQRM1();
                        if(openStatus == undefined) {
                            //插件未安装
                            CloseUSBQRM1();
                            RFCardError(102);
                            return;
                        }
                        if(openStatus != 0){
                            //发卡器未连接
                            CloseUSBQRM1();
                            RFCardError(103);
                            return;
                        }
                        var oldCardData = ReadCardQRM1();
                        if(oldCardData == ''){
                            //无法识别感应卡
                            CloseUSBQRM1();
                            RFCardError(104);
                            return;
                        }
                        if(guestQRM1(info.cardData) != 0) {
                            //无法识别感应卡
                            CloseUSBQRM1();
                            RFCardError(104);
                            return;
                        }
                        var RetData = ReadCardQRM1();
                        BuzzerQRM1(20);
                        CloseUSBQRM1();
                        ajaxRequest('/Home/Order/reportRFData',{
                            "hotel" : window.currentHotel,
                            "serialNum": info.serialNum,
                            "cardData": RetData,
                            "userRoom":obj.data('userRoom'),  
                            "oldCardData": oldCardData,
                        }, 'post', function(data){
                            var row = obj.closest('.row');
                            var printCount = parseInt(row.find('.printCount').text());
                            if(printCount <= 0){
                                row.find('.lostRf').removeClass('text-disable');
                            }
                            printCount++;
                            row.find('.printCount').text(printCount);
                            if(status == 0){
                                layer.msg(lang('RF.8'), {icon: 1});
                            }else{
                                layer.msg(lang('RF.9'), {icon: 1});
                            };
                        }, null);                             
                    }                        
                    hideCardLoading();                       
                }                
            };
        }, function(error) {
            modalAlert(error.responseJSON.info);
        });         
    }
    //读卡数据
    $('#submitRfcardRead').on('click',function(){
        $('#RF-roomName').val('');
        $('#RF-userName').val('');
        $('#RF-userMobile').val('');
        $('#RF-userIdentity').val('');
        $('#RF-batchNo').val('');
        $('#RF-writeTime').val('');
        $('#RF-availableTime').val('');
        $('#RF-roomStyle').val('');
        $('#RF-starsTime').val('');
        if(!isIE){
            RFCardError(101);
        }else{
            showCardLoading();
            var isTypeJiu = $('#objectHTML').attr('isTypeJiu');
            var isTypeSi = $('#objectHTML').attr('isTypeSi');
            var whichType  = $('#requestMeizhuCardTypeV9').prop('checked') ? 2 : 3;
            if(whichType == '2'){
                if(isTypeJiu != 'true') {
                    var objectHTML = '<OBJECT id="IEV957M1CLS" classid="clsid:FAA6C3FA-CBB7-48B8-8269-016E259C4E2B"></OBJECT>';
                    $('#objectHTML').append(objectHTML).attr('isTypeJiu', true);
                }
                var openStatus = OpenUSB57M1();
                if(openStatus == undefined) {
                    //插件未安装
                    CloseUSB57M1();
                    RFCardError(102);
                    return;
                }
                if(openStatus != 0){
                    //发卡器未连接
                    CloseUSB57M1();
                    RFCardError(103);
                    return;
                }
                if(ReadCard57M1() == ''){
                    //无法识别感应卡
                    CloseUSB57M1();
                    RFCardError(104);
                    return;
                }
                var RetData = ReadCard57M1();
                Buzzer57M1(20);
                CloseUSB57M1(); 
                readRfCard(RetData);
            }else if(whichType == '3'){
                if(isTypeSi != 'true'){
                  var objectHTML = '<OBJECT id=IEQRM1CLS classid="clsid:E7A609EB-0AE9-46C6-BB9C-5D8ECE503D7C"></OBJECT>';
                  $('#objectHTML').append(objectHTML).attr('isTypeSi',true);
                }
                var openStatus = OpenUSBQRM1();
                if(openStatus == undefined) {
                    //插件未安装
                    CloseUSBQRM1();
                    RFCardError(102);
                    return;
                }
                if(openStatus != 0){
                    //发卡器未连接
                    CloseUSBQRM1();
                    RFCardError(103);
                    return;
                }
                if(ReadCardQRM1() == ''){
                    //无法识别感应卡
                    CloseUSBQRM1();
                    RFCardError(104);
                    return;
                }
                var RetData = ReadCardQRM1();
                BuzzerQRM1(20);
                CloseUSBQRM1();
                readRfCard(RetData);
            }              
        }

    });
    //注销RF卡
    var EraseRF = function(){
        if(!isIE){
            RFCardError(101);
        }else{
            var isTypeJiu = $('#objectHTML').attr('isTypeJiu');
            var isTypeSi = $('#objectHTML').attr('isTypeSi');
            var whichType  = $('#requestMeizhuCardTypeV9').prop('checked') ? 2 : 3;
            if(whichType == '2'){
                if(isTypeJiu != 'true') {
                    var objectHTML = '<OBJECT id="IEV957M1CLS" classid="clsid:FAA6C3FA-CBB7-48B8-8269-016E259C4E2B"></OBJECT>';
                    $('#objectHTML').append(objectHTML).attr('isTypeJiu', true);
                }
                var openStatus = OpenUSB57M1();
                if(openStatus == undefined) {
                    //插件未安装
                    CloseUSB57M1();
                    RFCardError(102);
                    return;
                }
                if(openStatus != 0){
                    //发卡器未连接
                    CloseUSB57M1();
                    RFCardError(103);
                    return;
                }
                if(ReadCard57M1() == ''){
                    //无法识别感应卡
                    CloseUSB57M1();
                    RFCardError(104);
                    return;
                }
                var RetData = ReadCard57M1();
                ajaxRequest('/Home/Order/queryRFData', {
                    'hotel':window.currentHotel,
                    "cardData": RetData,
                }, 'post', function(){
                    window.guest = '57M1';
                    $('#cancelledModal').modal('show');
                }, function(error) {
                    if(error.responseJSON.status == 512){
                        RFCardError(106);
                    }
                });
            }else if(whichType == '3'){
                if(isTypeSi != 'true'){
                  var objectHTML = '<OBJECT id=IEQRM1CLS classid="clsid:E7A609EB-0AE9-46C6-BB9C-5D8ECE503D7C"></OBJECT>';
                  $('#objectHTML').append(objectHTML).attr('isTypeSi',true);
                }
                var openStatus = OpenUSBQRM1();
                if(openStatus == undefined) {
                    //插件未安装
                    CloseUSBQRM1();
                    RFCardError(102);
                    return;
                }
                if(openStatus != 0){
                    //发卡器未连接
                    CloseUSBQRM1();
                    RFCardError(103);
                    return;
                }
                if(ReadCardQRM1() == ''){
                    //无法识别感应卡
                    CloseUSBQRM1();
                    RFCardError(104);
                    return;
                }
                var RetData = ReadCardQRM1();
                ajaxRequest('/Home/Order/queryRFData', {
                    'hotel':window.currentHotel,
                    "cardData": RetData,
                }, 'post', function(){
                    window.guest = 'QRM1';
                    $('#cancelledModal').modal('show');
                }, function(error) {
                    if(error.responseJSON.status == 512){
                        RFCardError(106);
                    }
                });
            }              
        }
    }
    $('#submitRfcardCancel').on('click', function(){
        ajaxRequest('/Home/Order/checkClient', {
            'hotel':window.currentHotel,
            'deviceType':$('#requestMeizhuCardTypeV9').prop('checked') ? 2 : 3
        }, 'post', function(data){
            if(!data.data.isClientAvailable)
            {
                EraseRF();
            }
        }, function(error) {
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });    
    $('#submitCancelledModal').click(function(){
        var cardData = 'C00|M00000000|Y000|B000|F000|R000|X1|S1701010000|I1701010000|O1701010000';
        if(window.guest == '57M1'){
            guest57M1(cardData);
            Buzzer57M1(20);
            layer.msg(lang('RF.10'), {icon: 1});
            CloseUSB57M1();
        }else{
            guestQRM1(cardData);
            BuzzerQRM1(20);
            layer.msg(lang('RF.10'), {icon: 1});
            CloseUSBQRM1();
        };
        $('#cancelledModal').modal('hide');
    });
    var readRfCard = function(rFCard){
        hideCardLoading();
        ajaxRequest('/Home/Order/queryRFData', {
            'hotel':window.currentHotel,
            'cardData':rFCard,
        }, 'post', function(data) {
            var info = data.data;
            $('#RF-roomName').val(info.room);
            $('#RF-userName').val(info.owner);
            $('#RF-userMobile').val(info.mobile);
            $('#RF-userIdentity').val(info.identity);
            $('#RF-batchNo').val(info.batchno);
            $('#RF-writeTime').val(info.createtime);
            $('#RF-availableTime').val(info.endtime);
            $('#RF-roomStyle').val(info.roomType);
            $('#RF-starsTime').val(info.starttime);
        }, function(error) {
            if(error.responseJSON.status == 512){
                RFCardError(106);
            }
        });        
    };
    //离开页面触发
    $(window).unload(function() {
        var isTypeJiu = $('#objectHTML').attr('isTypeJiu');
        var isTypeSi = $('#objectHTML').attr('isTypeSi'); 
        if(isTypeSi == 'true'){
            FreeDriver();
        };
        if(isTypeJiu == 'true'){
            FreeDriver57M1();
        };        
    });
    // 切换显示打印房卡
    $('.orderPrint').on('click', function(e) {
        var orderPrintContent = $('#orderPrintContent');
        $('#orderPrintContainer').html('');
        // 使用订单数据,初始化打印房卡页面数据
        var templatePrintOrderItem = $('#templatePrintOrder');
        var templatePrintUserItem = $('#templatePrintUser');
        var canPrintCount = 0;
        for(var i = 0; i < window.orderDetailInfo.rooms_qr.length; i++) {
            if (window.orderDetailInfo.rooms_qr[i].status == window.orderStatus.checkin || window.orderDetailInfo.rooms_qr[i].status == window.orderStatus.needOut) {
                var templatePrintOrder = $(templatePrintOrderItem.clone().html());
                // 放置页面显示数据
                templatePrintOrder.find('.info').text(window.orderDetailInfo.rooms_qr[i].room);
                if(window.orderDetailInfo.rooms_qr[i].hour>0){
                    templatePrintOrder.find('.startdate').text(window.orderDetailInfo.rooms_qr[i].starttime);
                    templatePrintOrder.find('.night').text(window.orderDetailInfo.rooms_qr[i].hour+lang('hour'));     
                    templatePrintOrder.find('.enddate').closest('.text-primary').addClass('hidden');
                    
                }else{                     
                    templatePrintOrder.find('.startdate').text(getDate(window.orderDetailInfo.rooms_qr[i].startdate).customFormat(lang('tip.date')));
                    templatePrintOrder.find('.enddate').text(getDate(window.orderDetailInfo.rooms_qr[i].checkoutdate).customFormat(lang('tip.date')));
                    templatePrintOrder.find('.night').text(window.orderDetailInfo.rooms_qr[i].realnight+lang('nights'));
                }  
                // 放置js需要获取的数据
                templatePrintOrder.find('.lostPrint').data('value', window.orderDetailInfo.rooms_qr[i].id);
    
                // 子订单入住人
                for(var j = 0; j < window.orderDetailInfo.rooms_qr[i].user.length; j++) {
                    if (parseInt(window.orderDetailInfo.rooms_qr[i].user[j].isdelete) === 1) {
                        continue;
                    }
                    
                    var templatePrintUser = $(templatePrintUserItem.clone().html());
                    // 放置页面显示数据
                    templatePrintUser.find('.username').text(window.orderDetailInfo.rooms_qr[i].user[j].name);
                    if(window.orderDetailInfo.rooms_qr[i].user[j].mobile != ''){
                        templatePrintUser.find('.usermobile').text('+'+window.orderDetailInfo.rooms_qr[i].user[j].areaCode+' '+window.orderDetailInfo.rooms_qr[i].user[j].mobile);
                    }
                    templatePrintUser.find('.printCount').text(window.orderDetailInfo.rooms_qr[i].user[j].printCount);
                    // 放置js需要获取的数据
                    templatePrintUser.find('input.checkbox-print').data('userroom', window.orderDetailInfo.rooms_qr[i].user[j].userRoom);
    
                    templatePrintOrder.append(templatePrintUser);
                }
                $('#orderPrintContainer').append(templatePrintOrder);
                canPrintCount++;   
            }else{             
                continue;
            }
        }

        if (canPrintCount === 0) {
            $('#orderPrintContainer').html('<div class="text-center" style="padding: 8px 0px;">'+lang('print')+'</div>');
            $('#orderPrintAllContainer').addClass('hidden');
            $('#orderPrintContent').find('.modal-footer').addClass('hidden');
        } else {
            componentHandler.upgradeAllRegistered();
            formInlineRight($('#submitPrint'));
            $('#orderPrintAllContainer').find('.printAllCheckbox')[0].MaterialCheckbox.uncheck();
            $('#orderPrintAllContainer').removeClass('hidden');
            $('#orderPrintContent').find('.modal-footer').removeClass('hidden');
        }

        var activeContent = $('#orderHistoryContent');
        orderPrintContent.siblings().addClass('hidden');
        orderPrintContent.removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));
        if (activeContent.hasClass('hidden')) {
            activeContent = $('#orderInitContent');
            if(activeContent.hasClass('hidden')){
                activeContent = $('#orderQRContent');
            }
        }
        activeContent.addClass('hidden');
        $('#orderPrintContent').removeClass('hidden').css('left', activeContent.css('left')).css('top', activeContent.css('top'));
    });
    
    var role = $('#orderEditContent').attr('data-role');
    if(role == 1){
        $('#orderEditContent').inputValidate({
            submit: {
                query: '#editOrderConfirm'
            },
            inputs: [{
                query: '.orderUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.orderUserMobile',
                required: false,
                regexp: window.commonRegexp.mobile,
                message: lang('tip.phoneForma')
            }, {
                query: '.addOrderPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }, {
                query: '.addOrderReceive',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.gathering')
            }, {
                query: '#editOrderRemark',
                regexp: window.commonRegexp.nameLength255,
                required: false,
                message: lang('tip.remark')
            }, {
                query: '.orderLongUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.addOrderLongPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }, {
                query: '.orderHourUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.addOrderHourPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }]
        });        
    }else{
        $('#orderEditContent').inputValidate({
            submit: {
                query: '#editOrderConfirm'
            },
            inputs: [{
                query: '.orderUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.addOrderPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }, {
                query: '.addOrderReceive',
                regexp: window.commonRegexp.roomTypePrice,
                required: false,
                message: lang('tip.gathering')
            }, {
                query: '#editOrderRemark',
                regexp: window.commonRegexp.nameLength255,
                required: false,
                message: lang('tip.remark')
            }, {
                query: '.orderLongUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.addOrderLongPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }, {
                query: '.orderHourUserName',
                regexp: window.commonRegexp.nameLength20,
                message: lang('tip.xingming')
            }, {
                query: '.addOrderHourPrice',
                regexp: window.commonRegexp.roomTypePrice,
                message: lang('tip.room')
            }]
        });          
    }

    
    //计算房间价格
    var calculateRoomPrice = function(date, room, night){
  	   var total_price = 0;
  	  var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g),'/'))).getTime()/1000);
  	  for(var i = 0; i < night; i++){
  		  total_price += parseFloat(window.roomPrices[room + '_' + timestamp]);
  		  timestamp += 86400;
  	  }
  	  return total_price.toFixed(2);
    };
    
        
    //计算钟点房房间价格
    var calculateHourRoomPrice = function(date, room, hour){
        var total_price = 0;
        var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g),'/'))).getTime()/1000);
        for(var i=0;i<window.hourprice[room + '_' + timestamp].length;i++){
            if(window.hourprice[room + '_' + timestamp][i] == hour){
                total_price = window.hourpay[room + '_' + timestamp][i];
            }
        }
        return parseFloat(total_price).toFixed(2);  
    };  
    
    //计算长租房房间价格
    var calculateLongRoomPrice = function(date, room, longs){
        var total_price = 0;
        var timestamp = parseInt((new Date(date.replace(new RegExp(/-/g),'/'))).getTime()/1000);
        var starttimestamp = parseInt(getDate(window.startDate).getTime()/1000);
        if(starttimestamp>timestamp){
            timestamp += (starttimestamp-timestamp);
        }
        for(var i = 0; i < longs; i++){
            total_price += parseFloat(window.longprice[room + '_' + timestamp]);
        }
        return total_price.toFixed(2);
    };     
    
    //房间切换计算价格
    $('#editOrderRoom').on('click', '.editOrderRoomIdMenu li>a', function(e) {
    	var item = $(this);
        var room = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var date = parentTr.find('.editOrderRoomCheckIn').data('value');
        var night = parentTr.find('.editOrderRoomNight').data('value');
        var editOrderRooms = $('#editOrderRoom');
        var selectedDateFormat = editOrderRooms.find('table:first-child .editOrderRoomCheckIn').data('value');
        var selectedTime = (new Date(date)).getTime();
        var sectionStartTime = (new Date(window.startDate)).getTime();
        var sectionEndTime = sectionStartTime + 30 * 86400000;
        if( selectedTime < sectionStartTime || selectedTime > sectionEndTime ){
            formInlineTip($('#editOrderConfirm'), lang('date.scope'));
        }else{
            formInlineTip($('#editOrderConfirm'), '');
            parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, room ,night));
            item.parents('.dropdown').attr('data-change', '1');
        }    
        calculateEditContentTotal();
    });
    //入住晚数切换计算价格
    $('#editOrderRoom').on('click', '.editOrderRoomNightMenu li>a', function(e) {
    	var item = $(this);
        var night = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var date = parentTr.find('.editOrderRoomCheckIn').data('value');
        var room = parentTr.find('.editOrderRoomId').data('value');
        var editOrderRooms = $('#editOrderRoom');
        var selectedDateFormat = editOrderRooms.find('table:first-child .editOrderRoomCheckIn').data('value');
        var selectedTime = (new Date(date)).getTime();
        var sectionStartTime = (new Date(window.startDate)).getTime();
        var sectionEndTime = sectionStartTime + 30 * 86400000;
        if( selectedTime < sectionStartTime || selectedTime > sectionEndTime ){
            formInlineTip($('#editOrderConfirm'), lang('date.scope'));
        }else{
            formInlineTip($('#editOrderConfirm'), '');
            parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, room ,night));        
            item.parents('.dropdown').attr('data-change', '1');
        }
        parentTr.find('.editOrderRoomNight .info').text(night);
        calculateEditContentTotal();
    });
    //入住时间切换
    $('#editOrderRoom').on('click', '.editOrderRoomCheckInMenu li>a', function(e) {
    	var item = $(this);
        var date = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderRoomTr');
        var room = parentTr.find('.editOrderRoomId').data('value');
        var night = parentTr.find('.editOrderRoomNight').data('value');
        parentTr.find('.addOrderPrice').val(calculateRoomPrice(date, room ,night));
        item.parents('.dropdown').attr('data-change', '1');
    });
    //入住钟点房时间切换
    $('#editOrderRoom').on('click', '.addOrderRoomHourMenu li>a', function(e) {
        var item = $(this);
        var hour = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderHourRoomTr');
        var room = parentTr.find('.editOrderHourRoomId').data('value');
        var date = parentTr.find('.editOrderHourRoomCheckIn').data('time');
        parentTr.find('.addOrderHourPrice').val(calculateHourRoomPrice(date, room ,hour));
        item.parents('.dropdown').attr('data-change', '1');
        calculateEditHourContentTotal();
    });    
    // 钟点房间切换计算价格
    $('#editOrderRoom').on('click', '.editOrderHourRoomIdMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var itemValue = liItem.data('value');
        var parentTr = item.parents('.addOrderHourRoomTr');
        var date = parentTr.find('.editOrderHourRoomCheckIn').data('time');
        var hour = parseInt(parentTr.find('.addOrderHourRoom .info').text());
        parentTr.find('.addOrderHourPrice').val(calculateHourRoomPrice(date, itemValue, hour));
        item.parents('.dropdown').attr('data-change', '1');
        calculateEditHourContentTotal();
    });      
    // 长租间切换计算价格
    $('#editOrderRoom').on('click', '.editOrderLongRoomIdMenu li>a', function(e) {
        var item = $(this);
        var liItem = item.parents('li');
        var itemValue = liItem.data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var date = parentTr.find('.editOrderLongRoomCheckIn').data('value');
        var longs = parseInt(parentTr.find('.addOrderRoomLong .info').text().substr(0, 1));
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, itemValue, longs));
        calculateEditLongContentTotal();
    });  
    //长租入住时间切换
    $('#editOrderRoom').on('click', '.editOrderLongRoomCheckInMenu li>a', function(e) {
        var item = $(this);
        var date = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var room = parentTr.find('.editOrderLongRoomId').data('value');
        var longs = parseInt(parentTr.find('.addOrderRoomLong .info').text().substr(0, 1));
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, room ,longs));
    });    
    //入住长租房月数切换
    $('#editOrderRoom').on('click', '.addOrderRoomLongMenu li>a', function(e) {
        var item = $(this);
        var longs = item.parents('li').data('value');
        var parentTr = item.parents('.addOrderLongRoomTr');
        var room = parentTr.find('.editOrderLongRoomId').data('value');
        var date = parentTr.find('.editOrderLongRoomCheckIn').data('value');
        parentTr.find('.addOrderLongPrice').val(calculateLongRoomPrice(date, room ,longs));
        parentTr.find('.months .info').text(longs);
        calculateEditLongContentTotal();
    }); 

    //修改订单
    $('#editOrderConfirm').on('successSubmit.amos.inputValidate', function(e) {
        e.preventDefault();
        //获取数据值
        var params = {};
        var editConfirmButton = $(this);
        if(parseFloat(window.discountrule) >0 ){
            var vip = {'discountRule':window.discountrule,'discount':window.discount}
            params.vip = vip;
        }
        params.hotel = window.currentHotel;
        params.order = $(this).data('parent');
        params.channel = $('.editOrderChannel').data('value');
        window.receive = false;
        if(window.edithour){  
            params.detail = [];
            //默认获取第一个订单数据
            var firstDom = {};
            firstDom.orderRoomId = $('#editOrderRoom').find('.addOrderHourTableRoom:eq(0)').data('value');
            firstDom.roomId = $('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.editOrderHourRoomId').data('value');
            var hourElement = $('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.addOrderHourRoom').data('value');
            var startDateElement = $('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.editOrderHourRoomCheckIn').data('time')+' '+$('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.editOrderHourRoomCheckIn .info').text()+':00';
            firstDom.nights = 0;
            firstDom.hour = hourElement;
            firstDom.payment = $('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.addOrderHourPrice').val();
            firstDom.orderDate = startDateElement;
            firstDom.users = [];  
            $('#editOrderRoom').find('.addOrderHourTableRoom:first-child').find('.addOrderHourUserTr').each(function() {
                // 已删除的同住人不提交数据
                if ($(this).hasClass('justRemoved')) {
                    return true;
                }                
                var isStar =  $(this).find('.orderHourUserMobile').attr('data-star');
                if(isStar == '1'){
                    var mobile = '';
                }else{
                    var mobile = $(this).find('.orderHourUserMobile').val();
                }
                var identity = $(this).find('.orderHourUserID').val();
                var newIdentity = $(this).find('.orderHourUserID').attr('value');
                var address = $(this).find('.orderHourUserID').data('address');
                var sex = $(this).find('.orderHourUserID').data('sex');
                var nation = $(this).find('.orderHourUserID').data('nation');
                var orderUserItem = {
                    orderUser: $(this).data('orderuser'),
                    name: $(this).find('.orderHourUserName').val(),
                };
                var areaCode = $(this).find('.areaCodeValue').text().trim();
                if (areaCode !== '') {
                    orderUserItem.areaCode = areaCode;
                }
                if (mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                if (identity !== '' && identity != newIdentity) {
                    if(identity.indexOf("*") <= 0){
                        orderUserItem.identity = identity;
                    }
                }
                if (identity == '') {
                    orderUserItem.identity = "";
                }
                if(address !== undefined){
                    if(address.indexOf("*") <= 0){
                        orderUserItem.idaddress = address;
                    }
                };
                if(sex !== undefined){
                    orderUserItem.idsex = sex;
                };
                if(nation !== undefined){
                    orderUserItem.idnation = nation;
                };
                firstDom.users.push(orderUserItem);
            });    
            params.detail.push(firstDom);
            $('#editOrderRoom').find('.addOrderHourTableRoom:gt(0)').each(function() {
                var orderdetail = {};
                var me = $(this);
                if ($(this).data('value') != undefined) {
                    orderdetail.orderRoomId = $(this).data('value');
                } else {
                    orderdetail.orderRoomId = 0;
                }
                orderdetail.roomId = $(this).find('.editOrderHourRoomId').data('value');
                var hourElement = $(this).find('.addOrderHourRoom .info').text();
                var startDateElement = $(this).find('.editOrderHourRoomCheckIn').data('time')+' '+$(this).find('.editOrderHourRoomCheckIn .info').text()+':00';
                orderdetail.nights = 0;
                orderdetail.hour =parseInt(hourElement);
                orderdetail.payment = parseFloat($(this).find('.addOrderHourPrice').val());
                orderdetail.orderDate = startDateElement;
                orderdetail.users = [];
                $(this).find('.addOrderHourUserTr').each(function() {
                    // 已删除的同住人不提交数据
                    if ($(this).hasClass('justRemoved')) {
                        return true;
                    }
                    var isStar =  $(this).find('.orderHourUserMobile').attr('data-star');
                    
                    if(isStar == '1'){
                        var mobile = '';
                    }else{
                        var mobile = $(this).find('.orderHourUserMobile').val();
                    }
                    var identity = $(this).find('.orderHourUserID').val();
                    var newIdentity = $(this).find('.orderHourUserID').attr('value');
                    var address = $(this).find('.orderHourUserID').data('address');
                    var sex = $(this).find('.orderHourUserID').data('sex');
                    var nation = $(this).find('.orderHourUserID').data('nation');
                    var orderUserItem = {
                        orderUser: $(this).data('orderuser'),
                        name: $(this).find('.orderHourUserName').val(),
                    };
                    var areaCode = $(this).find('.areaCodeValue').text().trim();
                    if (areaCode !== '') {
                        orderUserItem.areaCode = areaCode;
                    }
                    if (mobile !== '') {
                        orderUserItem.mobile = mobile;
                    }
                    if (identity !== '' && identity != newIdentity) {
                        if(identity.indexOf("*") <= 0){
                            orderUserItem.identity = identity;
                        }
                    }
                    if (identity == '') {
                        orderUserItem.identity = "";
                    }
                    if(address !== undefined){
                        if(address.indexOf("*") <= 0){
                            orderUserItem.idaddress = address;
                        }
                    };
                    if(sex !== undefined){
                        orderUserItem.idsex = sex;
                    };
                    if(nation !== undefined){
                        orderUserItem.idnation = nation;
                    };
                    orderdetail.users.push(orderUserItem);
                });
                params.detail.push(orderdetail);
            });     
            params.receive = [];
            $('#editOrderReceive').find('.addOrderHourReceiveTr').each(function() {
                var money = {};
                money.category = $(this).find('.addOrderHourReceiveIsDeposit').data('value');
                money.type = $(this).find('.addOrderHourReceiveType').data('value');
                money.value = $(this).find('.addOrderHourReceive').val();
                money.transCurrencyId = $(this).find('.addMultiCurrencyHourType').data('value');
                if(!window.commonRegexp.roomTypePrice.test(money.value)){
                    formInlineTip(editConfirmButton, lang('tip.gathering'), 0);
                    window.receive = true;
                }
                params.receive.push(money);
            });
            var vipstatus = 5;
        }else if(window.editlong){
            params.detail = [];
            //默认获取第一个订单数据
            var firstDom = {};
            firstDom.orderRoomId = $('#editOrderRoom').find('.addOrderLongTableRoom:eq(0)').data('value');
            firstDom.roomId = $('#editOrderRoom').find('.addOrderLongTableRoom:first-child').find('.editOrderLongRoomId').data('value');
            var monthElement = $('#editOrderRoom').find('.addOrderLongTableRoom:first-child').find('.addOrderRoomLong .info').text();
            var startDateElement = $('#editOrderRoom').find('.addOrderLongTableRoom:first-child').find('.editOrderLongRoomCheckIn .info').text();
            firstDom.nights = 0;
            firstDom.month = parseInt(monthElement);
            firstDom.payment = $('#editOrderRoom').find('.addOrderLongTableRoom:first-child').find('.addOrderLongPrice').val();
            firstDom.orderDate = startDateElement;
            firstDom.users = [];  
            $('#editOrderRoom').find('.addOrderLongTableRoom:first-child').find('.addOrderLongUserTr').each(function() {
                // 已删除的同住人不提交数据
                if ($(this).hasClass('justRemoved')) {
                    return true;
                }                
                var isStar =  $(this).find('.orderLongUserMobile').attr('data-star');
                if(isStar == '1'){
                    var mobile = '';
                }else{
                    var mobile = $(this).find('.orderLongUserMobile').val();
                }
                var identity = $(this).find('.orderLongUserID').val();
                var newIdentity = $(this).find('.orderLongUserID').attr('value');
                var address = $(this).find('.orderLongUserID').data('address');
                var sex = $(this).find('.orderLongUserID').data('sex');
                var nation = $(this).find('.orderLongUserID').data('nation');
                var orderUserItem = {
                    orderUser: $(this).data('orderuser'),
                    name: $(this).find('.orderLongUserName').val(),
                };
                var areaCode = $(this).find('.areaCodeValue').text().trim();
                if (areaCode !== '') {
                    orderUserItem.areaCode = areaCode;
                }
                if (mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                if (identity !== '' && identity != newIdentity) {
                    if(identity.indexOf("*") <= 0){
                        orderUserItem.identity = identity;
                    }
                }
                if (identity == '') {
                    orderUserItem.identity = "";
                }
                if(address !== undefined){
                    if(address.indexOf("*") <= 0){
                        orderUserItem.idaddress = address;
                    }
                };
                if(sex !== undefined){
                    orderUserItem.idsex = sex;
                };
                if(nation !== undefined){
                    orderUserItem.idnation = nation;
                };
                firstDom.users.push(orderUserItem);
            });    
            params.detail.push(firstDom);
            $('#editOrderRoom').find('.addOrderLongTableRoom:gt(0)').each(function() {
                var orderdetail = {};
                var me = $(this);
                if ($(this).data('value') != undefined) {
                    orderdetail.orderRoomId = $(this).data('value');
                } else {
                    orderdetail.orderRoomId = 0;
                }
                orderdetail.roomId = $(this).find('.editOrderLongRoomId').data('value');
                var monthElement = $(this).find('.addOrderRoomLong .info').text();
                var startDateElement = $(this).find('.editOrderLongRoomCheckIn .info').text();
                orderdetail.nights = 0;
                orderdetail.month =parseInt(monthElement);
                orderdetail.payment = parseFloat($(this).find('.addOrderLongPrice').val());
                orderdetail.orderDate = startDateElement;
                orderdetail.users = [];
                $(this).find('.addOrderLongUserTr').each(function() {
                    // 已删除的同住人不提交数据
                    if ($(this).hasClass('justRemoved')) {
                        return true;
                    }
                    var isStar =  $(this).find('.orderLongUserMobile').attr('data-star');
                    
                    if(isStar == '1'){
                        var mobile = '';
                    }else{
                        var mobile = $(this).find('.orderLongUserMobile').val();
                    }
                    var identity = $(this).find('.orderLongUserID').val();
                    var newIdentity = $(this).find('.orderLongUserID').attr('value');
                    var address = $(this).find('.orderLongUserID').data('address');
                    var sex = $(this).find('.orderLongUserID').data('sex');
                    var nation = $(this).find('.orderLongUserID').data('nation');
                    var orderUserItem = {
                        orderUser: $(this).data('orderuser'),
                        name: $(this).find('.orderLongUserName').val(),
                    };
                    var areaCode = $(this).find('.areaCodeValue').text().trim();
                    if (areaCode !== '') {
                        orderUserItem.areaCode = areaCode;
                    }
                    if (mobile !== '') {
                        orderUserItem.mobile = mobile;
                    }
                    if (identity !== '' && identity != newIdentity) {
                        if(identity.indexOf("*") <= 0){
                            orderUserItem.identity = identity;
                        }
                    }
                    if (identity == '') {
                        orderUserItem.identity = "";
                    }
                    if(address !== undefined){
                        if(address.indexOf("*") <= 0){
                            orderUserItem.idaddress = address;
                        }
                    };
                    if(sex !== undefined){
                        orderUserItem.idsex = sex;
                    };
                    if(nation !== undefined){
                        orderUserItem.idnation = nation;
                    };
                    orderdetail.users.push(orderUserItem);
                });
                params.detail.push(orderdetail);
            });     
            params.receive = [];
            $('#editOrderReceive').find('.addOrderLongReceiveTr').each(function() {
                var money = {};
                money.category = $(this).find('.addOrderLongReceiveIsDeposit').data('value');
                money.type = $(this).find('.addOrderLongReceiveType').data('value');
                money.value = $(this).find('.addOrderLongReceive').val();
                money.transCurrencyId = $(this).find('.addMultiCurrencyLongType').data('value');
                if(!window.commonRegexp.roomTypePrice.test(money.value)){
                    formInlineTip(editConfirmButton, lang('tip.gathering'), 0);
                    window.receive = true;
                }
                params.receive.push(money);
            });       
            var vipstatus = 6;
        }else{
            params.detail = [];
            //默认获取第一个订单数据
            var firstDom = {};
            firstDom.orderRoomId = $('#editOrderRoom').find('.addOrderTableRoom:eq(0)').data('value');
            // $(this).data("value");
            firstDom.roomId = $('#editOrderRoom').find('.addOrderTableRoom:first-child').find('.editOrderRoomId').data('value');
            var nightElement = $('#editOrderRoom').find('.addOrderTableRoom:first-child').find('.editOrderRoomNight');
            var startDateElement = $('#editOrderRoom').find('.addOrderTableRoom:first-child').find('.editOrderRoomCheckIn');
            firstDom.nights = nightElement.data('value');
            // 如果订单是已退房订单,且没改动过晚数,把传到后台的晚数恢复到realnight
            if (window.orderDetailInfo.rooms[0].status === window.orderStatus.checkout && typeof(nightElement.parents('.dropdown').attr('data-change')) === 'undefined' && typeof(startDateElement.parents('.dropdown').attr('data-change')) === 'undefined') {
                firstDom.nights = window.orderDetailInfo.rooms[0].realnight;
            }
            firstDom.payment = $('#editOrderRoom').find('.addOrderTableRoom:first-child').find('.addOrderPrice').val();
            firstDom.orderDate = startDateElement.data('value');
            firstDom.users = [];
            $('#editOrderRoom').find('.addOrderTableRoom:first-child').find('.addOrderUserTr').each(function() {
                // 已删除的同住人不提交数据
                if ($(this).hasClass('justRemoved')) {
                    return true;
                }                
                var isStar =  $(this).find('.orderUserMobile').attr('data-star');
                if(isStar == '1'){
                    var mobile = '';
                }else{
                    var mobile = $(this).find('.orderUserMobile').val();
                }
                var areaCode = $(this).find('.areaCodeValue').text().trim();
                var identity = $(this).find('.orderUserID').val();
                var newIdentity = $(this).find('.orderUserID').attr('value');
                var address = $(this).find('.orderUserID').data('address');
                var sex = $(this).find('.orderUserID').data('sex');
                var nation = $(this).find('.orderUserID').data('nation');
                var orderUserItem = {
                    orderUser: $(this).data('orderuser'),
                    name: $(this).find('.orderUserName').val(),
                };
                if (areaCode !== '') {
                  orderUserItem.areaCode = areaCode;
                }
                if (mobile !== '') {
                    orderUserItem.mobile = mobile;
                }
                if (identity !== '' && identity != newIdentity) {
                    if(identity.indexOf("*") <= 0){
                        orderUserItem.identity = identity;
                    }
                }
                if (identity == '') {
                    orderUserItem.identity = "";
                }
                if(address !== undefined){
                    if(address.indexOf("*") <= 0){
                        orderUserItem.idaddress = address;
                    }
                };
                if(sex !== undefined){
                    orderUserItem.idsex = sex;
                };
                if(nation !== undefined){
                    orderUserItem.idnation = nation;
                };     
                firstDom.users.push(orderUserItem);
            });
            params.detail.push(firstDom);
            $('#editOrderRoom').find('.addOrderTableRoom:gt(0)').each(function() {
                var orderdetail = {};
                var me = $(this);
                if ($(this).data('value') != undefined) {
                    orderdetail.orderRoomId = $(this).data('value');
                } else {
                    orderdetail.orderRoomId = 0;
                }
                orderdetail.roomId = $(this).find('.editOrderRoomId').data('value');
                var nightElement = $(this).find('.editOrderRoomNight');
                var startDateElement = $(this).find('.editOrderRoomCheckIn');
                orderdetail.nights = nightElement.data('value');
                // 如果订单是已退房订单,且没改动过晚数,把传到后台的晚数恢复到realnight
                for (var orderDetailIndex = 1; orderDetailIndex < window.orderDetailInfo.rooms.length; orderDetailIndex++) {
                    if (parseInt(window.orderDetailInfo.rooms[orderDetailIndex].id) === parseInt(orderdetail.orderRoomId)) {
                        if (window.orderDetailInfo.rooms[orderDetailIndex].status === window.orderStatus.checkout && typeof(nightElement.parents('.dropdown').attr('data-change')) === 'undefined' && typeof(startDateElement.parents('.dropdown').attr('data-change')) === 'undefined') {
                            orderdetail.nights = window.orderDetailInfo.rooms[orderDetailIndex].realnight;
                        }
                    }
                }
                orderdetail.payment = parseFloat($(this).find('.addOrderPrice').val());
                orderdetail.orderDate = startDateElement.data('value');
                orderdetail.users = [];
                $(this).find('.addOrderUserTr').each(function() {
                    // 已删除的同住人不提交数据
                    if ($(this).hasClass('justRemoved')) {
                        return true;
                    }
                    var isStar =  $(this).find('.orderUserMobile').attr('data-star');
                    
                    if(isStar == '1'){
                        var mobile = '';
                    }else{
                        var mobile = $(this).find('.orderUserMobile').val();
                    }
                    var areaCode = $(this).find('.areaCodeValue').text().trim();
                    var identity = $(this).find('.orderUserID').val();
                    var newIdentity = $(this).find('.orderUserID').attr('value');
                    var address = $(this).find('.orderUserID').data('address');
                    var sex = $(this).find('.orderUserID').data('sex');
                    var nation = $(this).find('.orderUserID').data('nation');
                    var orderUserItem = {
                        orderUser: $(this).data('orderuser'),
                        name: $(this).find('.orderUserName').val(),
                    };
                    if (areaCode !== '') {
                      orderUserItem.areaCode = areaCode;
                    }
                    if (mobile !== '') {
                        orderUserItem.mobile = mobile;
                    }
                    if (identity !== '' && identity != newIdentity) {
                        if(identity.indexOf("*") <= 0){
                            orderUserItem.identity = identity;
                        }
                    }
                    if (identity == '') {
                        orderUserItem.identity = "";
                    }
                    if(address !== undefined){
                        if(address.indexOf("*") <= 0){
                            orderUserItem.idaddress = address;
                        }
                    };
                    if(sex !== undefined){
                        orderUserItem.idsex = sex;
                    };
                    if(nation !== undefined){
                        orderUserItem.idnation = nation;
                    };
                    orderdetail.users.push(orderUserItem);   
                });
                params.detail.push(orderdetail);
            });            
            params.receive = [];
            $('#editOrderReceive').find('.addOrderReceiveTr').each(function() {
                var money = {};
                money.category = $(this).find('.addOrderReceiveIsDeposit').data('value');
                money.type = $(this).find('.addOrderReceiveType').data('value');
                money.transCurrencyId = $(this).find('.addMultiCurrencyType').data('value');
                money.value = $(this).find('.addOrderReceive').val();
                params.receive.push(money);
            });
            var vipstatus = 4;
        }
        params.remark = $('#editOrderRemark').val();
        params.couponGetNo = window.orderDetailInfo.couponGetNo;
        if(window.receive){
            return false;
        }
        params.orderPayRecord = [];
        $('.editOrderReceiveModule').find('.editReceiptRefundTr').each(function() {
            var record = {};
            record.id = $(this).data('id');
            record.hotelPayId = $(this).find('.receiptPayStyle').data('value');
            record.transCurrencyId = $(this).find('.edit-currency').data('value');
            record.type = $(this).find('.receipt-or-refund ').data('value');
            record.pay = $(this).find('.refund-receipt').text();
            params.orderPayRecord.push(record);
        });        
        if(!getRoomVerification(vipstatus,params,$(this))){
            return false;
        }                
        ajaxRequest('/Home/Order/edit', params, 'post', function(data) {
            //隐藏对话框
            editConfirmButton.trigger('afterCommit');
            var orderParam = {};
            orderParam.hotel = params.hotel;
            orderParam.order = params.order;   
            ajaxRequest('/Home/Order/getOrder', orderParam, 'post', initOrderInfoSuccess, function(error) {
                hideMainLoading();
            });            
        }, function(data, obj) {
            hideMainLoading();
            if (typeof data.responseJSON == 'undefined') {
                formInlineTip($(obj), lang('tip.networkPoor'), 0);
            } else {
                formInlineTip($(obj), data.responseJSON.info, 0);
            }
        }, $(this));
    });
    $('#editOrderRoom').on('click','.areaCode',function(e){
        e.stopPropagation();
        e.preventDefault();
        var me = $(this);
        if(me.hasClass('open')){
           me.removeClass('open'); 
        }else{
           me.addClass('open'); 
        }
    });
    $('#editOrderRoom,#orderCheckInContent').on('click','.areaCode>.dropdown-menu li>a',function(){
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_code_cookie") != 'undefined') {
          $.cookie('area_code_cookie', value, { expires: 7, path: '/' });
        }
        window.discount = "";
        window.discountrule = "";
    });    
    // 打印订单
    var hexToString = function (str) {
        var val = '';
        for (var i = 0; i < str.length / 2; i++) {
            val += String.fromCharCode(parseInt(str.substr(2 * i, 2), 16));
        }
        return val;
    };
    var pt2px = function (ptValue) {
        var ptBase128 = $('#initOrderDetailPrint .printPage').width();
        return ptValue * (ptBase128 / 128) ;
    };
    // 打印初始化
    var printInit = function() {
        if (window.LODOPInstance == undefined) {
            window.LODOPInstance = getLodop();
        }
        window.LODOPInstance.PRINT_INIT(lang('printer.card'));
        window.LODOPInstance.SET_PRINT_PAGESIZE(3, 558, 0, '');
        window.LODOPPrintCount = 0;
    };
    // 添加一页打印页
    var addPrintPage = function(subOrderId, userRoom) {
        if (window.LODOPInstance == undefined) {
            printInit();
        }
        var hasRemark = window.orderDetailInfo.remark !== undefined && window.orderDetailInfo.remark !== '';
        var printHint1 = window.printCardSetting.tips1;
        var hasPrintHint1 = true;
        if (printHint1 === undefined || printHint1.length === 0) {
            hasPrintHint1 = false;
        }
        var printHint2 = window.printCardSetting.tips2;
        var hasPrintHint2 = true;
        if (printHint2 === undefined || printHint2.length === 0) {
            hasPrintHint2 = false;
        }
        var orderInfo = '';
        var printPages = '';
        var showName;
        var templatePrintPage = $($('#templatePrintDetail').clone().html());
        var userFound = false;
        for (i = 0; i < window.orderDetailInfo.rooms.length; i++) {
            orderInfo = window.orderDetailInfo.rooms[i];
            if ((orderInfo.status === window.orderStatus.checkin || orderInfo.status === window.orderStatus.needOut) && parseInt(subOrderId) === parseInt(orderInfo.id)) {
                templatePrintPage.find('.print-title').html(window.orderDetailInfo.hotelName);
                // 找到相应的用户
                for (j = 0; j < orderInfo.user.length; j++) {
                    if (parseInt(orderInfo.user[j].userRoom) === parseInt(userRoom)) {
                        if (orderInfo.user === undefined || orderInfo.user[j] === undefined || orderInfo.user[j].name === undefined) {
                            showName = '';
                        } else {
                            showName = orderInfo.user[j].name;
                        }
                        templatePrintPage.find('.print-detail-name').html(templatePrintPage.find('.print-detail-name').data('prefix') + showName);
                        templatePrintPage.find('.print-detail-room').html(templatePrintPage.find('.print-detail-room').data('prefix') + orderInfo.room);
                        templatePrintPage.find('.print-detail-start').html(templatePrintPage.find('.print-detail-start').data('prefix') + orderInfo.printStart);
                        templatePrintPage.find('.print-detail-end').html(templatePrintPage.find('.print-detail-end').data('prefix') + orderInfo.printEnd);
                        templatePrintPage.find('.print-detail-deposit').html(templatePrintPage.find('.print-detail-deposit').data('prefix') + window.orderDetailInfo.deposit);
                        if (hasPrintHint1) {
                            templatePrintPage.find('.print-detail-hint-1').css('display', 'block');
                            templatePrintPage.find('.print-detail-hint-1').html(printHint1);
                        } else {
                            templatePrintPage.find('.print-detail-hint-1').css('display', 'none');
                        }
                        if (hasPrintHint2) {
                            templatePrintPage.find('.print-detail-hint-2').css('display', 'block');
                            templatePrintPage.find('.print-detail-hint-2').html(printHint2);
                        } else {
                            templatePrintPage.find('.print-detail-hint-2').css('display', 'none');
                        }
                        if (hasRemark) {
                            templatePrintPage.find('.print-detail-remark').css('display', 'block');
                            templatePrintPage.find('.print-detail-remark').html(templatePrintPage.find('.print-detail-remark').data('prefix') + window.orderDetailInfo.remark);
                        } else {
                            templatePrintPage.find('.print-detail-remark').css('display', 'none');
                        }
                        printPages += templatePrintPage.prop('outerHTML');
                        userFound = true;
                        break;
                    }
                }
            } else {
                orderInfo = '';
            }

            if (userFound) {
                break;
            }
        }
        if (orderInfo === '') {
            return false;
        }

        $('#initOrderDetailPrint').html(printPages);
        var qrCodeStr;
        if (orderInfo.printType === 1) {
            qrCodeStr = orderInfo.printCard;
        } else {
            qrCodeStr = hexToString(orderInfo.printCard);
        }
        var canvasContainer = $('#initOrderDetailPrintQRCode');
        canvasContainer.html('');
        $('#initOrderDetailPrintQRCode').qrcode({
            width: 2000,
            height: 2000,
            text: qrCodeStr
        });
        var canvasElem = canvasContainer.find('canvas')[0];
        var imgData = canvasElem.toDataURL('image/png');
        $('#initOrderDetailPrint .print-detail-key').attr('src', imgData);

        if (window.LODOPPrintCount >= 1) {
            window.LODOPInstance.NEWPAGE();
        }
        window.LODOPInstance.ADD_PRINT_HTM(0, 0,"100%","100%",$('#initOrderDetailPrint').prop('outerHTML'));
        window.LODOPPrintCount++;
    };
    // 打开预览
    var togglePrintPreview = function() {
        if (window.LODOPInstance == undefined) {
            printInit();
        }        

        //指定打印机
        if(window.printCardSetting.printername)
        {
            window.LODOPInstance.SET_PRINTER_INDEXA(window.printCardSetting.printername);
        }          

        window.LODOPInstance.SET_SHOW_MODE("HIDE_PAPER_BOARD",1);
        window.LODOPInstance.SET_PREVIEW_WINDOW(0,1,1,600,400,"");//打印前弹出选择打印机的对话框
        window.LODOPInstance.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW",1);//打印后自动关闭预览窗口
        window.LODOPInstance.PREVIEW(); 
    };
    // 请求打印数据
    var getPrintQrcode = function(customCallback, errorCallback, triggerElement, subOrder, lost) {
        var params = {
            hotel: window.currentHotel,
            order: window.orderDetailInfo.id,
            subOrder: subOrder,
            lost: lost === true ? '1' : '0',
        };
        ajaxRequest('/Home/Order/printQrcode', params, 'post', function(data){
            var printDetailInfo = data.data;
            if(!printDetailInfo.isClientAvailable){
                window.printCardSetting = printDetailInfo.printSetting;
                window.orderDetailInfo.hotelName = printDetailInfo.hotelName;
                var printCardInfo = printDetailInfo.cardData;
                var printCardInfoItem;
                for (var i = 0; i < window.orderDetailInfo.rooms.length; i++) {
                    printCardInfoItem = printCardInfo[window.orderDetailInfo.rooms[i].id];
                    if (printCardInfoItem === undefined) {
                        continue;
                    }
    
                    window.orderDetailInfo.rooms[i].printStart = printCardInfoItem.startTime;
                    window.orderDetailInfo.rooms[i].printEnd = printCardInfoItem.endTime;
                    window.orderDetailInfo.rooms[i].printType = printCardInfoItem.type;
                    window.orderDetailInfo.rooms[i].printCard = printCardInfoItem.cardString;
                };
                customCallback(data);                
            };
            hideMainLoading();
        }, function(error) {
            hideMainLoading();
            errorCallback(error);
        }, triggerElement);
    };

    // 单选按钮影响全选按钮
    $('#orderPrintContent').on('change', '.checkbox-print', function() {
        var length = $('#orderPrintContent').find('.printCheckbox').length;
        var checkedLength = $('#orderPrintContent').find('.printCheckbox.is-checked').length;
        if (checkedLength === 0 || checkedLength < length) {
            $('#orderPrintAllContainer').find('.printAllCheckbox')[0].MaterialCheckbox.uncheck();
        } else if (checkedLength === length) {
            $('#orderPrintAllContainer').find('.printAllCheckbox')[0].MaterialCheckbox.check();
        }
    });
    // 全选按钮
    $('.checkbox-printAll').on('change', function() {
        if ($(this).prop('checked') === true) {
            $('#orderPrintContent').find('.printCheckbox').each(function() {
                $(this)[0].MaterialCheckbox.check();
            });
        } else {
            $('#orderPrintContent').find('.printCheckbox').each(function() {
                $(this)[0].MaterialCheckbox.uncheck();
            });
        }
    });
    // 批量打印
    $('#orderPrintContent').on('click', '#submitPrint', function(e){
        e.preventDefault();
        var submitBtn = $('#submitPrint');
        var getPrintQrcodeParams = [];
        var checkBoxInstance = [];

        $('#orderPrintContent').find('.printOrder').each(function() {
            var printOrder = $(this);
            var getPrintQrcodeParamItem = {
                userRoom: [],
            };
            // 找出勾选的用户
            printOrder.find('.checkbox-print').each(function() {
                if ($(this).prop('checked') === true) {
                    getPrintQrcodeParamItem.userRoom.push($(this).data('userroom'));
                    // 保留需要打印的用户的checkbox对象
                    checkBoxInstance.push($(this));
                }
            });

            if (getPrintQrcodeParamItem.userRoom.length > 0) {
                getPrintQrcodeParamItem.id = printOrder.find('.lostPrint').data('value');
                getPrintQrcodeParams.push(getPrintQrcodeParamItem);
            }
        });

        if (getPrintQrcodeParams.length > 0) {
            getPrintQrcode(function(data) {
                // 本地增加打印次数
                for (var k in checkBoxInstance) {
                    var printCount = checkBoxInstance[k].parents('.row').find('.printCount');
                    printCount.text(parseInt(printCount.text().trim()) + 1);
                }

                // 初始化打印预览页面
                printInit();
                for (var i in getPrintQrcodeParams) {
                    for (var j in getPrintQrcodeParams[i].userRoom) {
                        addPrintPage(getPrintQrcodeParams[i].id, getPrintQrcodeParams[i].userRoom[j]);
                    }
                }
                togglePrintPreview();
            }, function(error) {
                var info = '';
                if (typeof error.responseJSON === 'undefined') {
                    info = lang('tip.system');
                } else if (error.responseJSON.status == 602) {
                    info = error.responseJSON.data + error.responseJSON.info;
                } else {
                    info = error.responseJSON.info;
                }
                formInlineTip(submitBtn, info);
            }, submitBtn, getPrintQrcodeParams, false);
        }
    });
    // 挂失打印
    $('#orderPrintContent').on('click', '.lostPrint', function(e){
        e.preventDefault();
        var submitBtn = $(this);
        var userRoom = [];
        var printOrder = submitBtn.parents('.printOrder');
        var subOrderId = submitBtn.data('value');
        var getPrintQrcodeParams = [{
            id: subOrderId,
            userRoom: [],
        }];
        printOrder.find('input.checkbox-print').each(function() {
            getPrintQrcodeParams[0].userRoom.push($(this).data('userroom'));
        });

        getPrintQrcode(function(data) {
            // 本地增加打印次数
            printOrder.find('.printCount').each(function() {
                var oldPrintCount = $(this).text().trim();
                $(this).text(parseInt(oldPrintCount) + 1);
            });

            // 初始化打印预览页面
            printInit();
            for (var i in getPrintQrcodeParams[0].userRoom) {
                addPrintPage(getPrintQrcodeParams[0].id, getPrintQrcodeParams[0].userRoom[i]);
            }
            togglePrintPreview();
        }, function(error) {
            var info = '';
            if (parseInt(error.responseJSON.status) == 602) {
                info = error.responseJSON.data + error.responseJSON.info;
            }else if (typeof error.responseJSON === 'undefined' || parseInt(error.responseJSON.status) != 509) {
                info = lang('tip.system');
            }else {
                info = error.responseJSON.info;
            }
            tooltipWrong(submitBtn, info, 1, 0.5);
        }, submitBtn, getPrintQrcodeParams, true);
    });
    //退房状态修改日期
    function getChangeDate(table){
        var differ_day = parseInt(Math.abs(today - getDate(window.startDate) ) / 86400000); 
        var newCalendar = table.find(".editOrderRoomCheckInMenu li");
        for(var j=0;j<newCalendar.length;j++){
            if(j<differ_day){
               newCalendar.eq(j).show(); 
            }else{
               newCalendar.eq(j).hide(); 
            }
        };          
    };
    $('#orderEditContent').on('click','.editOrderRoomCheckIn',function(){
        var table = $(this).closest('table');
        var orderRoomValue = table.data('value');
        $.each(window.orderDetailInfo.rooms, function(index, value) {
            if(value.id == orderRoomValue){
               if(value.status == lang('status.checkOut')){
                    getChangeDate(table);
                }
            }
        }); 
    });      
    $('#orderEditContent').on('click','.nights',function(){
        var table = $(this).closest('table');
        var orderRoomValue = table.data('value');
        var liveData = table.find('.addOrderRoomTr .editOrderRoomCheckIn>.info').text();
        var differNights = parseInt(Math.abs(today - getDate(liveData) ) / 86400000);
        $.each(window.orderDetailInfo.rooms, function(index, value) {
            if(value.id == orderRoomValue){                
               if(value.status == lang('status.checkOut')){
                    var nightsHtml = table.find("#nights .editOrderRoomNightMenu");
                    var newNight = nightsHtml.find("li");
                    if(newNight.eq(0).data('value') != 0){
                        nightsHtml.prepend('<li data-value="0"><a href="javascript:void(0);">0'+lang('nights')+'</a></li>');
                        for(var j=0;j<newNight.length;j++){
                            if(differNights>j){newNight.eq(j).show();}else{newNight.eq(j).hide();};
                        };                         
                    }else{
                        for(var j=0;j<newNight.length;j++){
                            if(differNights>=j){newNight.eq(j).show();}else{newNight.eq(j).hide();};
                        };                         
                    }
                }
            }
        });    
    });     
    $('#btnPrintOrderInfo').on('click', function(){
        $btn = $(this);
        var initContent = $('#orderInitContent');
        var orderValue = initContent.data('parent');
        ajaxRequest('/Home/Order/printOrder', {hotel:window.currentHotel,printType:1,order:orderValue}, 'post', function(data){
            hideMainLoading();
            data = data.data;
            var oderInfo = window.orderDetailInfo;
            if(!data.isClientAvailable){
                //初始化
                if (window.LODOPInstance == undefined) {
                    window.LODOPInstance = getLodop();
                }
                window.LODOPInstance.PRINT_INIT(lang('printer.order'));
                
                //按打印纸张不同处理打印内容
                var printOrderInfoContent = '';
                if(data.printerpaper=='X58')
                {                
                    window.LODOPInstance.SET_PRINT_PAGESIZE(3, 558, 0, '');
                    printOrderInfoContent = $($('#templatePrintOrderInfo_X58').clone().html());
                    printOrderInfoContent.find('.title').html(data.hotelName);
                    printOrderInfoContent.find('.print_time').html(lang('printer.time')+data.printTime);
                    printOrderInfoContent.find('.user_name span').html(oderInfo.name);
                    if(parseInt(data.printmobile))
                    {
                        printOrderInfoContent.find('.user_mobile').show();
                        if(oderInfo.mobile != ''){
                            printOrderInfoContent.find('.user_mobile').find('span').html('+'+oderInfo.areaCode+'&nbsp;'+oderInfo.mobile);
                        }                
                    }
                    if(parseInt(data.printidentity))
                    {
                        printOrderInfoContent.find('.user_identity').show().find('span').html(oderInfo.identity);                    
                    }
                    var roomsContainer = printOrderInfoContent.find('.rooms');
                    var tmpRoomContent = roomsContainer.html();
                    roomsContainer.html('');
                    for(var i=0,l=oderInfo.rooms.length; i<l; i++)
                    {
                        var roomContent = $(tmpRoomContent);
                        var roomInfo = oderInfo.rooms[i];
                        roomContent.find('.room_name').html('['+roomInfo.room+']');
                        if(roomInfo.hour > 0){
                            roomContent.find('.room_date').html(roomInfo.starttime);
                            roomContent.find('.room_night').html(roomInfo.hour + lang('hour'));
                        }else{
                            roomContent.find('.room_date').html(roomInfo.checkintime + '<br/>' + roomInfo.checkouttime);
                            roomContent.find('.room_night').html(roomInfo.night + lang('nights'));
                        }
                        roomContent.find('.room_price').html(roomInfo.pay);
                        roomsContainer.append(roomContent.prop('outerHTML'));
                    }
                    var payContainer = printOrderInfoContent.find('.pay-html');
                    var tmpPayContent = payContainer.html();
                    payContainer.html('');
                    for(var i=0,l=oderInfo.payHistory.receivedInfo.length; i<l; i++)
                    {
                        var payContent = $(tmpPayContent);
                        var payInfo = oderInfo.payHistory.receivedInfo[i];
                        if(payInfo.type == 0){
                            payContent.find('.orderReceive').text(lang('print.1')+payInfo.name+lang('print.6'));
                        }else{
                            payContent.find('.orderReceive').text(lang('print.2')+payInfo.name+lang('print.6'));
                        }
                        payContent.find('.payment').text(payInfo.pay);
                        payContainer.append(payContent.prop('outerHTML'));
                    };     
                    for(var i=0,l=oderInfo.payHistory.otherReceivedInfo.length; i<l; i++)
                    {
                        var payContent = $(tmpPayContent);
                        var payInfo = oderInfo.payHistory.otherReceivedInfo[i];
                        if(payInfo.hotelPayId != 0){
                            payContent.find('.orderReceive').text(payInfo.otherCostName+'('+payInfo.name+lang('print.6'));
                            payContent.find('.payment').text(payInfo.pay);
                            payContainer.append(payContent.prop('outerHTML'));
                        }
                    };           
                    var refundContainer = printOrderInfoContent.find('.refund-html');
                    var tmpRefundContent = refundContainer.html();
                    refundContainer.html('');
                    for(var i=0,l=oderInfo.payHistory.refundInfo.length; i<l; i++)
                    {
                        var refundContent = $(tmpRefundContent);
                        var refundInfo = oderInfo.payHistory.refundInfo[i];
                        if(refundInfo.type == 2){
                            refundContent.find('.orderRefund').text(lang('print.3')+payInfo.name+lang('print.5'));
                        }else{
                            refundContent.find('.orderRefund').text(lang('print.4')+payInfo.name+lang('print.5'));
                        }
                        refundContent.find('.refundment').text(refundInfo.pay);
                        refundContainer.append(refundContent.prop('outerHTML'));
                    };                 
                    printOrderInfoContent.find('.other_pay_money span').html(parseFloat(parseFloat(oderInfo.otherReceivePrice)+parseFloat(oderInfo.otherUncollectePrice)).toFixed(2));
                    printOrderInfoContent.find('.pay_money span').html(oderInfo.orig);
                    printOrderInfoContent.find('.pay_discount span').html(oderInfo.pay);
                    printOrderInfoContent.find('.remark span').html(oderInfo.remark);
                    if(data.tips1)
                    {
                        printOrderInfoContent.find('.tips1').show().html(data.tips1);       
                            
                    }
                    if(data.tips2)
                    {
                        printOrderInfoContent.find('.tips2').show().html(data.tips2);                 
                    }                
                    
                    //打印联数
                    var printContent = '';
                    for(var printCount = parseInt(data.printtimes); printCount>0; printCount--)
                    {
                        window.LODOPInstance.ADD_PRINT_HTM(0, 0, "100%", "100%", printOrderInfoContent.prop('outerHTML'));
                        if(printCount>1)
                        {
                            window.LODOPInstance.NEWPAGE();
                        }
                    }
                }
                else
                {
                    window.LODOPInstance.SET_PRINT_PAGESIZE(3, 2100, 0, '');
                    printOrderInfoContent = $($('#templatePrintOrderInfo_A4').clone().html());
                    printOrderInfoContent.find('.title').html(data.hotelName);
                    printOrderInfoContent.find('.print_time').html(lang('printer.time')+data.printTime);
                    printOrderInfoContent.find('.user_name span').html(oderInfo.name);
                    if(parseInt(data.printmobile))
                    {
                        printOrderInfoContent.find('.user_mobile').show();
                        if(oderInfo.mobile !== ''){
                            printOrderInfoContent.find('.user_mobile').find('span').html('+'+oderInfo.areaCode+'&nbsp;'+oderInfo.mobile); 
                        }                   
                    }
                    if(parseInt(data.printidentity))
                    {
                        printOrderInfoContent.find('.user_identity').show().find('span').html(oderInfo.identity);                    
                    }
                    var roomsContainer = printOrderInfoContent.find('.rooms');
                    var tmpRoomContent = roomsContainer.html();
                    roomsContainer.html('');
                    for(var i=0,l=oderInfo.rooms.length; i<l; i++)
                    {
                        var roomContent = $(tmpRoomContent);
                        var roomInfo = oderInfo.rooms[i];
                        roomContent.find('.room_name').html(roomInfo.room);
                        roomContent.find('.room_price').html(roomInfo.pay);
                        if(roomInfo.hour > 0){
                            roomContent.find('.room_date').html(roomInfo.starttime);
                            roomContent.find('.room_night').html(roomInfo.hour + lang('hour'));
                            printOrderInfoContent.find('.data-word').text(lang('liveData'));
                        }else{
                            roomContent.find('.room_date').html(roomInfo.checkindate.slice(0,16) + ' - ' + roomInfo.printcheckouttime.slice(0,16));
                            roomContent.find('.room_night').html(roomInfo.night + lang('nights'));
                        }
                        roomsContainer.append(roomContent.prop('outerHTML'));
                    }
                    printOrderInfoContent.find('.other_pay_money span').html(parseFloat(parseFloat(oderInfo.otherReceivePrice)+parseFloat(oderInfo.otherUncollectePrice)).toFixed(2));
                    printOrderInfoContent.find('.pay_money span').html(oderInfo.orig);
                    printOrderInfoContent.find('.pay_discount span').html(oderInfo.pay);
                    printOrderInfoContent.find('.pay_receipt span').html(oderInfo.receipt);
                    printOrderInfoContent.find('.pay_deposit span').html(oderInfo.deposit);
                    printOrderInfoContent.find('.refund_receipt span').html((oderInfo.refundPrice == "" ? 0 : parseFloat(oderInfo.refundPrice)).toFixed(2));
                    printOrderInfoContent.find('.refund_deposit span').html((oderInfo.refundDeposit == ""  ? 0 : parseFloat(oderInfo.refundDeposit)).toFixed(2));
                    printOrderInfoContent.find('.remark span').html(oderInfo.remark);
                    var payReceiptBox = printOrderInfoContent.find('.pay_receipt_box');
                    var payDepositBox = printOrderInfoContent.find('.pay_deposit_box');
                    var payReceiptBox_much = printOrderInfoContent.find('.pay_receipt_box_much');
                    var payDepositBox_much = printOrderInfoContent.find('.pay_deposit_box_much');
                    payReceiptBox.html('');
                    payDepositBox.html('');
                    payReceiptBox_much.html('');
                    payDepositBox_much.html('');
                    payReceiptBoHtml = '';
                    payDepositHtml = '';
                    payReceiptBoHtml_much = '';
                    payDepositHtml_much = '';
                    for(var i=0,l=oderInfo.payHistory.receivedInfo.length; i<l; i++)
                    {
                        var payInfo = oderInfo.payHistory.receivedInfo[i];
                        if(payInfo.type == 0){
                            payReceiptBoHtml += "<div><span>"+payInfo.name+"</span></div>";
                            payReceiptBoHtml_much += "<div>：<span>"+payInfo.pay+"</span></div>";
                        }else{
                            payDepositHtml += "<div><span>"+payInfo.name+"</span></div>";
                            payDepositHtml_much += "<div>：<span>"+payInfo.pay+"</span></div>";
                        }
                    };      
                    for(var i=0,l=oderInfo.payHistory.otherReceivedInfo.length; i<l; i++)
                    {
                        var payInfo = oderInfo.payHistory.otherReceivedInfo[i];
                        if(payInfo.hotelPayId != 0){
                            payReceiptBoHtml += "<div><span>"+payInfo.name+"</span></div>";
                            payReceiptBoHtml_much += "<div>：<span>"+payInfo.pay+"&nbsp;&nbsp;("+payInfo.otherCostName+")</span></div>";
                        }
                    };                  
                    payReceiptBox.append(payReceiptBoHtml);   
                    payDepositBox.append(payDepositHtml);  
                    payReceiptBox_much.append(payReceiptBoHtml_much);   
                    payDepositBox_much.append(payDepositHtml_much);      
                    if(oderInfo.payHistory.refundInfo.length>0){
                        printOrderInfoContent.find('.refund-box').show();
                        var refundReceiptBox = printOrderInfoContent.find('.refund_receipt_box');
                        var refundDepositBox = printOrderInfoContent.find('.refund_deposit_box');
                        var refundReceiptBox_much = printOrderInfoContent.find('.refund_receipt_box_much');
                        var refundDepositBox_much = printOrderInfoContent.find('.refund_deposit_box_much');
                        refundReceiptBox.html('');
                        refundDepositBox.html('');
                        refundReceiptBox_much.html('');
                        refundDepositBox_much.html('');
                        refundReceiptBoHtml = '';
                        refundDepositHtml = '';
                        refundReceiptBoHtml_much = '';
                        refundDepositHtml_much = '';
                        for(var i=0,l=oderInfo.payHistory.refundInfo.length; i<l; i++)
                        {
                            var payInfo = oderInfo.payHistory.refundInfo[i];
                            if(payInfo.type == 2){
                                refundReceiptBoHtml += "<div><span>"+payInfo.name+"</span></div>";
                                refundReceiptBoHtml_much += "<div>：<span>"+payInfo.pay+"</span></div>";
                            }else{
                                refundDepositHtml += "<div><span>"+payInfo.name+"</span></div>";
                                refundDepositHtml_much += "<div>：<span>"+payInfo.pay+"</span></div>";
                            }
                        };        
                        refundReceiptBox.append(refundReceiptBoHtml);   
                        refundDepositBox.append(refundDepositHtml);  
                        refundReceiptBox_much.append(refundReceiptBoHtml_much);   
                        refundDepositBox_much.append(refundDepositHtml_much);                        
                    }else{
                        printOrderInfoContent.find('.refund-box').hide();
                    };
                    
                    if(data.tips1)
                    {
                        printOrderInfoContent.find('.tips1').show().html(data.tips1);                 
                    }
                    if(data.tips2)
                    {
                        printOrderInfoContent.find('.tips2').show().html(data.tips2);                 
                    }                
                    //打印联数
                    
                    var printContent = '';
                    for(var printCount = parseInt(data.printtimes); printCount>0; printCount--)
                    {
                        window.LODOPInstance.ADD_PRINT_HTM(0, 0, "100%", "100%", printOrderInfoContent.prop('outerHTML'));
                        if(printCount>1)
                        {
                            window.LODOPInstance.NEWPAGE();
                        }                        
                    }
          
                };
                
                //指定打印机
                if(data.printername)
                {
                    window.LODOPInstance.SET_PRINTER_INDEXA(data.printername);
                }
                
                //预览或直接打印
                if(parseInt(data.preview)){
                    window.LODOPInstance.SET_SHOW_MODE("HIDE_PAPER_BOARD",1);
                    var previewMode = 2;
                    if(data.printerpaper=='X58')
                    {
                        previewMode = 1;
                    }
                    window.LODOPInstance.SET_PREVIEW_WINDOW(previewMode, 1, 1, 800, 600, "");
                    //打印后自动关闭预览窗口
                    window.LODOPInstance.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW",1);
                    window.LODOPInstance.PREVIEW();
                }else{
                    window.LODOPInstance.PRINT();
                }  
            };         
        }, function(error) {
            hideMainLoading();
            formInlineTip($('#btnPrintOrderInfo'), error.responseJSON.info);
        }, $btn);
    });
    //身份认证
    var authenticationModal = $('#authenticationModal');
    var changeAuthenticationModal = $('#changeAuthenticationModal');
    $('#orderInitContent').on('click','.authentication',function(){
        var btn = $(this);
        var orderUser = btn.data('orderuser');
        var param = {};
        param.hotel = window.currentHotel;
        param.orderUser = orderUser;
        ajaxRequest('/Home/Order/getOrderUserInfo', param, 'post', function(data) {
            var info = data.data;
            authenticationModal.find('.userName').text(info.name);
            authenticationModal.find('.userIdCard').text(info.identity);
            authenticationModal.find('.user-tip-Name').text(info.name);
            authenticationModal.find('.user-tip-idcard').text(info.identity);
            authenticationModal.find('.user-tip-nation').text(info.idnation);
            authenticationModal.find('.user-tip-address').text(info.idaddress);
            if(parseInt(info.idsex) == 1){
                authenticationModal.find('.user-tip-gender').text(lang('male'));
            }else if(parseInt(info.idsex) == 0){
                authenticationModal.find('.user-tip-gender').text(lang('female'));
            }else{
                authenticationModal.find('.user-tip-gender').text('');
            }
            authenticationModal.show();
        }, function(error) {

        }); 
        authenticationModal.show();
    });
    authenticationModal.on('click',function(e){
        e.stopPropagation();
        authenticationModal.hide();
    }).on('click','.modal-content',function(e){
        e.stopPropagation();
        authenticationModal.show();
    });
    $('#orderEditContent').on('click','.change-authentication',function(){
        var btnTr = $(this).closest('tr');
        var orderUser = btnTr.data('orderuser');
        if(window.edithour){
            var orderName =  btnTr.find('.orderHourUserName');
            var orderUserID =  btnTr.find('.orderHourUserID');
        }else if(window.editlong){
            var orderName =  btnTr.find('.orderLongUserName');
            var orderUserID =  btnTr.find('.orderLongUserID');
        }else{
            var orderName =  btnTr.find('.orderUserName');
            var orderUserID =  btnTr.find('.orderUserID'); 
        }
        var param = {};
        param.hotel = window.currentHotel;
        param.orderUser = orderUser;
        ajaxRequest('/Home/Order/getOrderUserInfo', param, 'post', function(data) {
            var info = data.data;
            $('#idcard-gender').attr('value',info.idsex);
            $('#idcard-nation').val(info.idnation);
            $('#idcard-address').val(info.idaddress);
            if(orderName.val() != ''){
                $('#idcard-name').val(orderName.val());
            }else{
                $('#idcard-name').val(info.name);
            }
            if(orderUserID.val() != ''){
                $('#idcard-num').val(orderUserID.val());
            }else{
                $('#idcard-num').val(info.identity);
            }
            $('#changeIdcardInfo').attr('data-orderUser',orderUser);
            changeAuthenticationModal.show();
            $('#changeIdcardInfo').unbind('click').bind('click', function(e) {
                e.stopPropagation();
                var address = $('#idcard-address').val();
                var gender = $('#idcard-gender').val();
                var nation = $('#idcard-nation').val();
                orderName.val($('#idcard-name').val());
                orderUserID.val($('#idcard-num').val());
                if(info.idaddress != address){
                    orderUserID.attr('data-address',address);
                }
                if(info.idsex != gender){
                    orderUserID.attr('data-sex',gender);
                }
                if(info.idnation != nation){
                    orderUserID.attr('data-nation',nation);
                }
                changeAuthenticationModal.hide();
            }); 
            $('#clearIdcardInfo').unbind('click').bind('click', function(e) {
                e.stopPropagation();
                $('#idcard-gender').val('');
                $('#idcard-nation').val('');
                $('#idcard-address').val('');
                $('#idcard-name').val('');
                $('#idcard-num').val('');
            });             
            
        }, function(error) {

        });     
    });
    changeAuthenticationModal.on('click',function(e){
        e.stopPropagation();
        changeAuthenticationModal.hide();
    }).on('click','.modal-content',function(e){
        e.stopPropagation();
        changeAuthenticationModal.show();
    });  
    
    //验证会员卡
    var confirmVIPcardInfo = $('#confirmVIPcardInfo');
    var memberInfoModal = $('#memberInfoModal');
    var editgetMembershipVerification = function(info,submitTrigger,params){
        var confirmVIPcardInfo = $('#confirmVIPcardInfo');
        var memberInfoModal = $('#memberInfoModal');
        var orderparams = params;
        $('#getvipmobile').data('submitTrigger',submitTrigger);
        $('#getvipmobile').data('params',params);
        confirmVIPcardInfo.data('submitTrigger',submitTrigger);
        memberInfoModal.find('.card-username').text('');
        memberInfoModal.find('.card-grade').text('');
        memberInfoModal.find('.card-balance').text('');
        memberInfoModal.find('.card-charge').text('');
        memberInfoModal.find('#getvipmobile').val('');
        var testGetCode = $('.test-get-code');
        var param = {};
        var vipCard = {};
        vipCard.cardMobile = info.mobile;
        vipCard.cardAreaCode = info.areaCode;
        param.hotel = window.currentHotel;
        param.mobile = info.mobile;
        param.areaCode = info.areaCode;
        ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
            if(data.data.length != 0){
                confirmVIPcardInfo.removeClass('disabled');
                testGetCode.removeClass('disabled');
                var vipinfo = data.data[0];
                memberInfoModal.find('.card-username').text(vipinfo.name);
                memberInfoModal.find('.card-grade').text(vipinfo.levelname);
                memberInfoModal.find('.card-balance').text(vipinfo.cardPrice);
                memberInfoModal.find('.card-charge').text(info.price.toFixed(2));
                memberInfoModal.find('.areaCodeValue').text(info.areaCode);
                memberInfoModal.find('#getvipmobile').val(vipinfo.mobile);
                orderparams.vipCard = vipCard; 
                confirmVIPcardInfo.data('orderparams',orderparams);
            }else{
                confirmVIPcardInfo.addClass('disabled');
                testGetCode.addClass('disabled');
            }
        }, function(data) {
            confirmVIPcardInfo.addClass('disabled');
            testGetCode.addClass('disabled');
        });        
        memberInfoModal.find('.form-group ').removeClass('has-error');
        memberInfoModal.modal('show');   
    }; 
    confirmVIPcardInfo.click(function(){
        var submitTrigger = $(this).data('submitTrigger');
        var submitBtn = submitTrigger.attr('id');
        var orderparams = confirmVIPcardInfo.data('orderparams');       
        if(submitBtn == 'editOrderConfirm' || submitBtn == 'checkInConfirm'){
            ajaxRequest('/Home/Order/verifyWithMobile', {
                "hotel": window.currentHotel,
                "vcode": $('#vipVerificationCode').val(),
            }, 'post', function(data) {
                if(submitBtn == 'editOrderConfirm' ){
                    ajaxRequest('/Home/Order/edit', orderparams, 'post', function(data) {
                        //隐藏对话框
                        submitTrigger.trigger('afterCommit');
                        var orderParam = {};
                        orderParam.hotel = orderparams.hotel;
                        orderParam.order = orderparams.order;   
                        ajaxRequest('/Home/Order/getOrder', orderparams, 'post', initOrderInfoSuccess, function(error) {
                            hideMainLoading();
                        });            
                    }, function(data, obj) {
                        hideMainLoading();
                        if (typeof data.responseJSON == 'undefined') {
                            formInlineTip($(obj), lang('tip.networkPoor'), 0);
                        } else {
                            formInlineTip($(obj), data.responseJSON.info, 0);
                        }
                    }, submitTrigger);
                }else{
                    ajaxRequest('/Home/Order/checkin', orderparams, 'post', function(){
                        submitTrigger.trigger('afterBlrzCommit');
                        ajaxRequest('/Home/Order/getOrder', {
                            'hotel':window.currentHotel,
                            'order':orderparams.order,
                        }, 'post', initOrderInfoSuccess, function(error) {
                            hideMainLoading();
                        });
                    },checkInOrderError,submitTrigger);                
                };
                memberInfoModal.modal('hide');
            }, function(error) {
                if(typeof error.responseJSON == 'undefined') {
                    formInlineTip(confirmVIPcardInfo,lang('tip.networkPoor'), 0);
                } else {
                    formInlineTip(confirmVIPcardInfo, error.responseJSON.info, 0);
                }
            });               
        }
  
    });    
    $('#getvipmobile').blur(function(){
        var submitTrigger = $(this).data('submitTrigger');
        var submitBtn = submitTrigger.attr('id');    
        if(submitBtn == 'editOrderConfirm' || submitBtn == 'checkInConfirm'){
            var memberInfoModal = $('#memberInfoModal');
            var info = {
                mobile:$(this).val(),
                areaCode:memberInfoModal.find('.areaCodeValue').text(),
                price:window.membershipMobile.price
            };         
            editgetMembershipVerification(info,submitTrigger,$(this).data('params'));            
        }
    }); 
    var getRoomVerification = function(status,params,that){
        var getVerification = false;
        var price = 0;
        if(status == 4){
            var receiveTr = $('#editOrderReceive .addOrderReceiveTr');
            var room = $('#editOrderRoom .addOrderTableRoom').eq(0).find('.addOrderUserTr').eq(0);
            var mobile = room.find('.orderUserMobile');
        }else if(status == 5){
            var receiveTr = $('#editOrderReceive .addOrderHourReceiveTr');
            var room = $('#editOrderRoom .addOrderHourTableRoom').eq(0).find('.addOrderHourUserTr').eq(0);
            var mobile = room.find('.orderHourUserMobile');
        }else if(status == 6){
            var receiveTr = $('#editOrderReceive .addOrderLongReceiveTr');
            var room = $('#editOrderRoom .addOrderLongTableRoom').eq(0).find('.addOrderLongUserTr').eq(0);
            var mobile = room.find('.orderLongUserMobile');
        }else if(status == 7){
            var receiveTr = $('#checkInForm .addOrderReceiveTr');
            var room = $('#checkInUsers .addOrderTable').eq(0).find('.addOrderUserTr').eq(0);
            var mobile = room.find('.checkInOrderUserMobile');
        }
        receiveTr.each(function() {
            var value = $(this).find('td').eq(1).find('.info').text();
            if(value == lang('recharge.8')){
                getVerification = true;
                var vipPrice = $(this).find('td').eq(3).find('input').val();
                if(vipPrice == ''){
                    vipPrice = 0;
                }
                price += parseFloat(vipPrice);
            }
        });  
        if(getVerification){
            if(mobile.val() == ''){
                formInlineTip(that, lang('recharge.10'), 0);
            }else{
                var param = {};
                param.hotel = window.currentHotel;
                param.areaCode = room.find('.areaCodeValue').text();
                if(mobile.data('star') == 1){
                    param.mobile = window.trueMobile;
                }else{
                    param.mobile = mobile.val();
                }
                ajaxRequest('/Home/Customer/searchMobile', param, 'post', function(data) {
                    if(data.data.length == 0){
                        formInlineTip(that, lang('recharge.11'), 0);
                    }else{
                        if(price>0){
                            window.membershipMobile = {
                                mobile:param.mobile,
                                areaCode:room.find('.areaCodeValue').text(),
                                price:price
                            };    
                            editgetMembershipVerification(window.membershipMobile,that,params);                            
                        }else{
                            formInlineTip(that, lang('recharge.12'), 0);
                        }
                    }
                }, function(data) {
                    formInlineTip(that, lang('recharge.11'), 0);
                });                 
            };             
            return false;
        }else{
            return true;
        };
    }     
    //押金隐藏会员卡
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive').on('click','tr>td:nth-child(2)>div>a',function(){
        var liEle =  $(this).closest('.dropdown').find('.dropdown-menu li');
        var value =  $(this).closest('tr').find('td:nth-child(1)>div>a').data('value');
        if(value != 0){
            liEle.each(function(){
                if($(this).find('a').text() == lang('recharge.8')){
                    $(this).addClass('hidden');
                }
            });
        }else{
            liEle.each(function(){
                if($(this).find('a').text() == lang('recharge.8')){
                    $(this).removeClass('hidden');
                }
            });
        }
    });
    //会员卡隐藏币种
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive,#orderCheckInContent').on('click','tr>td:nth-child(3)>div>a',function(){
        var liEle =  $(this).closest('.dropdown').find('.dropdown-menu');
        var value =  $(this).closest('tr').find('td:nth-child(2)>div>a').text().trim();
        if(value == lang('recharge.8')){
            liEle.addClass('hidden');
        }else{
            liEle.removeClass('hidden');
        }
    });
    
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive,.receiptAppend,.refundAppend,.receiptAlerdyProject,#orderCheckInContent').on('click','tr>td:nth-child(2)>div>ul>li>a',function(e){
        var btn = $(this);
        var tdEle = btn.closest('tr').find('td:nth-child(3)');
        var dropdown = tdEle.find('[data-toggle="dropdown"]');
        var value =  $(this).text().trim();
        if(value == lang('recharge.8')){
            tdEle.find('.dropdown-menu').addClass('hidden');
            dropdown.attr('data-value',dropdown.data('default'));
            dropdown.find('.info').text(dropdown.data('name'));
        }else{
            tdEle.find('.dropdown-menu').removeClass('hidden');
        }
    });       
    
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive,.receiptAppend,.refundAppend,.receiptAlerdyProject').on('click','tr>td:nth-child(1)>div>ul>li>a',function(e){
        var btn = $(this);
        var tdEle = btn.closest('tr').find('td:nth-child(2)');
        var liEle =  tdEle.find('.dropdown-menu li').eq(0);
        var value = liEle.data('value');
        var textValue = liEle.find('a').text();
        var otherExpenseContent = btn.closest('li').find('.other-expense-content');
        var len = otherExpenseContent.find('.list').length;
        if(btn.text() == lang('type.cash') || btn.text() == lang('recharge.9') || btn.data('value') == 10){
            if(tdEle.find('div>a>.info').text() == lang('recharge.8')){
                tdEle.find('div>a').data('value',value);
                tdEle.find('div>a>.info').text(textValue);
            }
        }
        if(btn.data('value') == 10){
            e.stopPropagation();
            btn.closest('li').addClass('active').siblings('li').removeClass('active');
            if(len == 0){         
                layer.alert(lang('constant.noproject'), {
                  skin: 'layui-layer-me ',closeBtn: 0,shade: [0.01, '#1f1f1f'],
                  shadeClose:true,title:lang('commom.hint'),btn:lang('date.ensure'),
                });
            }else{
                if(otherExpenseContent.hasClass('hidden')){
                    otherExpenseContent.removeClass('hidden');
                }else{
                    otherExpenseContent.addClass('hidden');
                }
            }
        }else{
            tdEle.find('.order-agency-receipt').addClass('hidden');
            if(tdEle.find('div>a').data('value') == 0){
                tdEle.find('div>a').data('value',value);
                tdEle.find('div>a>.info').text(textValue);
            }
        }
    });     
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive,.receiptAppend,.refundAppend,.receiptAlerdyProject').on('click','tr>td:nth-child(1)',function(e){
        var value = $(this).find('[data-toggle="dropdown"]').data('value');
        if(value == 1 || value == 0){
            $('.other-expense-content').addClass('hidden');
        }else{
            if($('.other-expense-content .list').length>0){
                $('.other-expense-content').removeClass('hidden');
            }else{
                $('.other-expense-content').addClass('hidden');
            }
        }
    });      
    $('#addOrderReceive,#addOrderHourReceive,#addOrderLongReceive,#editOrderReceive,.receiptAppend,.refundAppend,.receiptAlerdyProject').on('click','.other-expense-content>.list',function(e){
        var btn = $(this);
        var value = btn.data('cost');
        var tdEle = btn.closest('tr').find('td:nth-child(1)');
        var tdEleReceive = btn.closest('tr').find('td:nth-child(2)');
        btn.addClass('active').siblings('.list').removeClass('active');
        tdEle.find('div>a').data('value',value);
        tdEle.find('div>a>.info').text(btn.text());
        tdEleReceive.find('.order-agency-receipt').removeClass('hidden');
    });
    $('#editOrderReceive').on('click','.other-expense-content>.list',function(e){
        if(window.edithour){
            calculateEditHourContentTotal()         ;   
        }else if(window.editlong){
            calculateEditLongContentTotal();
        }else{
            calculateEditContentTotal();           
        }     
    });       
});
var cancelOrderInitSuccess = function(data) {
    var payRecord = $('#payRecord');
    if (data.data.length === 0) {
        $('#cancelOrderPayEmpty').removeClass('hidden');
        $('#cancelOrderPayContainer').addClass('hidden');
        $('#cancelOrderRefoundDeposit').addClass('hidden');
    } else {
        $('#cancelOrderRefoundDeposit').removeClass('hidden');
        $('#cancelOrderPayContainer').removeClass('hidden');
        $('#cancelOrderPayEmpty').addClass('hidden');
        var records = '';
        $.each(data.data, function(index, record) {
            var template;
            if (record.type === '0') {
                template = $($('#templateOrderPayRecordReceipt').clone().html());
            } else if(record.type === '1') {
                template = $($('#templateOrderPayRecordDeposit').clone().html());
            } else{
                template = $($('#templateOrderPayRecordOther').clone().html());
                template.find('.source').html(record.otherCostName);
            }
            template.find('.paytype').html(record.name);
            template.find('.info').html(record.pay);
            records += template.prop('outerHTML');
        });
        payRecord.html(records);
    }
    hideMainLoading();
};

var initOrderInfoSuccess = function(data) {
    hideMainLoading();
    var orderInfo = data.data;
    window.orderDetailInfo = orderInfo;
    var initContent = $('#orderInitContent');
    var orderValue = orderInfo.id;
    var orderRoomValue = initContent.data('value');
    $('#checkInConfirm').attr('data-true',orderValue);
    $('#initCancel').attr('value-true',orderInfo.rooms[0].id);
    if (typeof orderRoomValue === 'undefined') {
        orderRoomValue = orderInfo.rooms[0].id;
    }
    var roomId = initContent.data('roomid');
    if (typeof roomId === 'undefined') {
        roomId = (orderInfo.rooms)[0].roomid;
    }
    initContent.data('value', orderRoomValue);
    initContent.data('parent', orderValue);
    initContent.data('roomid', roomId);
    // 根据关联房间数量显示不同信息块
    // 是否有子订单退款中
    if (orderInfo.refunding == 1) {
        initContent.find('.refunding').removeClass('hidden');
    } else {
        initContent.find('.refunding').addClass('hidden');
    }
    // 父订单应收金额，已收款，待收款，已收押金
    initContent.find('.payment').html(orderInfo.pay);
    initContent.find('.receipt').html(orderInfo.receipt);
    var depositContainer = initContent.find('.depositContainer');
    var payParent = initContent.find('.payParent');
    var payParentSum = initContent.find('.payParentSum');
    if (parseFloat(orderInfo.deposit) > 0) {
        depositContainer.removeClass('hidden');
        initContent.find('.deposit').html(orderInfo.deposit);
    } else {
        depositContainer.addClass('hidden');
    }
    if(parseFloat(orderInfo.refundDeposit) > 0){
        payParent.removeClass('hidden');
        initContent.find('.refund-pay-Container').html(orderInfo.refundDeposit);
    }else{
        payParent.addClass('hidden');
    }
    if(orderInfo.refundPrice != ''){
        payParentSum.removeClass('hidden');
        initContent.find('.refundContainer').html(orderInfo.refundPrice);
    }else{
        payParentSum.addClass('hidden');
    }
    
    var overdue = (parseFloat(orderInfo.pay) - parseFloat(orderInfo.receipt)).toFixed(2);
    overdue = overdue < 0 ? 0 : overdue;
    initContent.find('.overdue').html(overdue);
    // 父订单备注
    var remarkContainer = initContent.find('.remarkContainer');
    if (orderInfo.remark === undefined || orderInfo.remark === '') {
        remarkContainer.addClass('hidden');
    } else {
        remarkContainer.removeClass('hidden');
        initContent.find('.remark').html(orderInfo.remark);
    }
    // 入住人与房间信息
    var singleOrderInfoLeft = $('#singleOrderInfoLeft');
    var multipleOrderInfoLeft = $('#multipleOrderInfoLeft');
    var initOrderDetail = $('#initOrderDetail');
    var roomInfo = orderInfo.rooms[0];
    var printBtn;
    var printCount;
    if (orderInfo.rooms.length === 1) {
        multipleOrderInfoLeft.addClass('hidden');
    } else {
        multipleOrderInfoLeft.removeClass('hidden');
    }

    singleOrderInfoLeft.addClass('hidden');
    // 子订单模板渲染
    var templateOrderInfoItem = $('#templateOrderInfoItem');
    var templateOrderUserItem = $('#templateOrderUserItem');
    var templateOrderInfo;
    var relativeRoomInfo;
    var initOrderDetailHTML = '';
    var checkoutDate;
    var canPrintSubOrderCount = 0;
    for (var i = 0; i < orderInfo.rooms.length; i++) {
        templateOrderInfo = $(templateOrderInfoItem.clone().html());
        relativeRoomInfo = orderInfo.rooms[i];
        // 单个关联订单,隐藏房费
        if (orderInfo.rooms.length === 1) {
            templateOrderInfo.find('.roomPrice').addClass('hidden');
        }
        if(relativeRoomInfo.status == window.orderStatus.checkout || relativeRoomInfo.status == window.orderStatus.cancelled){
            templateOrderInfo.find('.realLive').html(lang('live'));
        }else{
            templateOrderInfo.find('.realLive').html(lang('zhu'));
        }
        templateOrderInfo.attr('data-value', relativeRoomInfo.id);
        checkoutDate = getDate(relativeRoomInfo.checkoutdate);
        if(parseInt(relativeRoomInfo.hour) >0){
            window.edithour = true;
            window.editlong = false;
            templateOrderInfo.find('.realLive').html(lang('gong'));
            templateOrderInfo.find('.night').html(relativeRoomInfo.hour+lang('hour'));
            templateOrderInfo.find('.startdate').html(relativeRoomInfo.starttime);
            templateOrderInfo.find('.enddate').closest('.text-primary').addClass('hidden');
        }else if(parseInt(relativeRoomInfo.month) >0){
            window.editlong = true;
            window.edithour = false;
            templateOrderInfo.find('.night').html(relativeRoomInfo.realnight+lang('night'));
            templateOrderInfo.find('.startdate').html(getDate(relativeRoomInfo.startdate).customFormat(lang('tip.date')));
            templateOrderInfo.find('.enddate').html(checkoutDate.customFormat(lang('tip.date')));
        }else{
            window.edithour = false;
            window.editlong = false;
            templateOrderInfo.find('.night').html(relativeRoomInfo.realnight+lang('night'));
            templateOrderInfo.find('.startdate').html(getDate(relativeRoomInfo.startdate).customFormat(lang('tip.date')));
            templateOrderInfo.find('.enddate').html(checkoutDate.customFormat(lang('tip.date')));
        }
        templateOrderInfo.find('.room').html(relativeRoomInfo.room);
        templateOrderInfo.find('.price').html(relativeRoomInfo.pay);
        // 添加订单入住人
        for(var j = 0; j < relativeRoomInfo.user.length; j++) {
            templateOrderUser = $(templateOrderUserItem.clone().html());
            templateOrderUser.find('.username').html(relativeRoomInfo.user[j].name);
            templateOrderUser.find('.usermobile').attr('data-orderuser', relativeRoomInfo.user[j].orderUser);
            templateOrderUser.find('.authentication').attr('data-orderuser', relativeRoomInfo.user[j].orderUser);
            if(relativeRoomInfo.user[j].mobile != ''){
                templateOrderUser.find('.usermobile').html('+'+relativeRoomInfo.user[j].areaCode+'&nbsp;'+relativeRoomInfo.user[j].mobile);
            }
            
            // 已入住订单,单独被删除的同住人,显示为已退房
            orderUserStatus = parseInt(relativeRoomInfo.user[j].isdelete) === 1 && relativeRoomInfo.status === lang('status.checkIn') ? window.orderStatus.checkout : relativeRoomInfo.status;
            templateOrderUser.find('.order-status').html(orderUserStatus);
            // 设置同住人是否可以重发短信
            if (parseInt(relativeRoomInfo.user[j].isdelete) === 0 && (window.roomItemType[relativeRoomInfo.roomid]['from'] === 1 || window.roomItemType[relativeRoomInfo.roomid]['from'] === 3) && orderInfo.canSendAgain === 1 && relativeRoomInfo.status === lang('status.checkIn') && relativeRoomInfo.user[j].mobile !== '' && checkoutDate.getDays(today) >= 0) {
                templateOrderUser.addClass('resend-active');
            } else {
                templateOrderUser.removeClass('resend-active');
            }
            templateOrderInfo.append(templateOrderUser);
        }
        initOrderDetailHTML += templateOrderInfo.prop('outerHTML');
        if (parseInt(relativeRoomInfo.id) === orderRoomValue) {
            roomInfo = relativeRoomInfo;
        };     
    };
    initOrderDetail.html(initOrderDetailHTML);
    // 房间信息、订单状态
    initContent.find('.modal-title .room').html(roomInfo.room);
    initContent.find('.modal-title .type').html(roomInfo.type);
    initContent.find('.modal-title .status').html(roomInfo.status);
    //查房状态
    var checkRoomName = [lang('checkroomstart'),lang('checkroomend'),lang('checkroomend')];
    if(roomInfo.checkRoom == 0 || roomInfo.checkRoom == 1 || roomInfo.checkRoom == 2){
        initContent.find('.check-status').removeClass('hidden').html(checkRoomName[roomInfo.checkRoom]);
    }else{
        initContent.find('.check-status').addClass('hidden');
    }
    if(roomInfo.checkRoom == 4){
        window.checkroom = true;
    }else{
        window.checkroom = false;
    }    
    // 打印按钮
    if (roomInfo.status === window.orderStatus.checkin || roomInfo.status === window.orderStatus.checkout || roomInfo.status === window.orderStatus.needOut)
    {
        $('#btnPrintOrderInfo').removeClass('hidden');
    }
    else
    {
        $('#btnPrintOrderInfo').addClass('hidden');
    }
    // 根据订单状态显示按钮
    var cancelBtn = $('#initCancel');
    var checkInBtn = $('#initCheckIn');
    var checkOutBtn = $('#initCheckOut');
    cancelBtn.addClass('hidden');
    checkInBtn.addClass('hidden');
    checkOutBtn.addClass('hidden');
    if (roomInfo.status === window.orderStatus.booked || roomInfo.status === window.orderStatus.paied) {
        var startDiffToday = getDate(roomInfo.startdate).getDays(today);
        var endDiffToday = getDate(roomInfo.enddate).getDays(today);
        cancelBtn.removeClass('hidden');
        if ((roomInfo.enddate == roomInfo.startdate && roomInfo.enddate == today.customFormat()) || (endDiffToday >= 0 && startDiffToday <= 0)) {
            checkInBtn.removeClass('hidden');
        };
    } else {
        if (roomInfo.status === window.orderStatus.checkin|| roomInfo.status === window.orderStatus.needOut) {
            cancelBtn.removeClass('hidden');
            checkOutBtn.removeClass('hidden');
        }
    };
    initContent.removeClass('hidden').siblings().addClass('hidden');
    $('#orderDetailModal').modal('show');
    hideMainLoading();
    //RF卡QR卡显示问题
    if (window.orderDetailInfo.rooms_rf.length == 0) {
        $('.orderRfcard').addClass('hidden');
    }else{
        $('.orderRfcard').removeClass('hidden');
    }
    if (window.orderDetailInfo.rooms_qr.length == 0) {
        $('.orderPrint').addClass('hidden');
    }else{
        $('.orderPrint').removeClass('hidden');
    }  
    // 使用订单数据,初始化打印RF卡页面数据
    $('#orderRfContainer').html('');
    var orderQRContent = $('#orderQRContent');
    var templateRfOrderItem = $('#templateRfOrder');
    var templateRfUserItem = $('#templateRfUser');
    var canPrintCount = 0;
    for(var i = 0; i < window.orderDetailInfo.rooms_rf.length; i++) {
        if (window.orderDetailInfo.rooms_rf[i].status == window.orderStatus.checkin || window.orderDetailInfo.rooms_rf[i].status == window.orderStatus.needOut ) {
	        var templateRfOrder = $(templateRfOrderItem.clone().html());
	        // 放置页面显示数据
	        if(window.orderDetailInfo.rooms_rf[i].hour>0){
	            templateRfOrder.find('.startdate').html(window.orderDetailInfo.rooms_rf[i].starttime);
	            templateRfOrder.find('.night').text(window.orderDetailInfo.rooms_rf[i].hour+lang('hour'));     
	            templateRfOrder.find('.enddate').closest('.text-primary').addClass('hidden');
	        }else if(window.orderDetailInfo.rooms_rf[i].month>0){
	            templateRfOrder.find('.startdate').text(getDate(window.orderDetailInfo.rooms_rf[i].startdate).customFormat(lang('tip.date')));
	            templateRfOrder.find('.enddate').text(getDate(window.orderDetailInfo.rooms_rf[i].checkoutdate).customFormat(lang('tip.date')));
	            templateRfOrder.find('.night').text(window.orderDetailInfo.rooms_rf[i].realnight+lang('night')); 
	        }else{
	            templateRfOrder.find('.startdate').text(getDate(window.orderDetailInfo.rooms_rf[i].startdate).customFormat(lang('tip.date')));
	            templateRfOrder.find('.enddate').text(getDate(window.orderDetailInfo.rooms_rf[i].checkoutdate).customFormat(lang('tip.date')));
	            templateRfOrder.find('.night').text(window.orderDetailInfo.rooms_rf[i].realnight+lang('night')); 
	        }
	        templateRfOrder.find('.info').text(window.orderDetailInfo.rooms_rf[i].room);
	        // 子订单入住人
	        for(var j = 0; j < window.orderDetailInfo.rooms_rf[i].user.length; j++) {
	            if (parseInt(window.orderDetailInfo.rooms_rf[i].user[j].isdelete) === 1) {
	                continue;
	            }
	            
	            var templateRfUser = $(templateRfUserItem.clone().html());
	            // 放置页面显示数据
	            templateRfUser.find('.username').text(window.orderDetailInfo.rooms_rf[i].user[j].name);
	            templateRfUser.find('.usermobile').text(window.orderDetailInfo.rooms_rf[i].user[j].mobile);
	            templateRfUser.find('.printCount').text(window.orderDetailInfo.rooms_rf[i].user[j].rfCount);
	            templateRfUser.find('.printRfCard').data('value', window.orderDetailInfo.rooms_rf[i].id);
	            templateRfUser.find('.printRfCard').data('userRoom', window.orderDetailInfo.rooms_rf[i].user[j].userRoom);
	            templateRfUser.find('.lostRf').data('value', window.orderDetailInfo.rooms_rf[i].id);
	            templateRfUser.find('.lostRf').data('userRoom', window.orderDetailInfo.rooms_rf[i].user[j].userRoom);
	            templateRfOrder.append(templateRfUser);
	        }
	        $('#orderRfContainer').append(templateRfOrder);
        	canPrintCount++;            
        }else{
        	continue;
        }
    }
    if (canPrintCount === 0) {
        $('#orderQRContent .warm-prompt').hide();
        $('#orderRfContainer').html('<div class="text-center" style="padding: 8px 0px;">'+lang("RF.7")+'</div>');
    } else {
        componentHandler.upgradeAllRegistered();
        $('#orderQRContent .warm-prompt').show();
    }
    var cardCount = $('#orderRfContainer .row');
    for(var i=0;i<cardCount.length-1;i++){
        card_Count = parseInt(cardCount.eq(i+1).find('.printCount').text());
        if(card_Count<=0){
            cardCount.eq(i+1).find('.lostRf').addClass('text-disable');
        }
    }   
    $('.form-group').removeClass('has-error'); 
};
/* exported showMainLoading */
var showMainLoading = function() {
    $('#mainLoading').removeClass('hidden');
};
/* exported hideMainLoading */
var hideMainLoading = function() {
    $('#mainLoading').addClass('hidden');
};
var showCardLoading = function() {
    $('#cardLoading').removeClass('hidden');
};
/* exported hideMainLoading */
var hideCardLoading = function() {
    $('#cardLoading').addClass('hidden');
};